CSS元素垂直水平居中

文章介绍了如何使用CSS调整行内和块级元素的布局,包括text-align与line-height设置,以及绝对定位、transform实现居中,以及flex布局的使用,展示了三种不同的布局方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.子元素是行内元素

父元素设置text-align:center; line-height设置为父元素的高度

  <style>
    .container {
      text-align: center;
      line-height: 200px;
      height: 200px;
  }
  </style>
  <body>
    <div class="container">
      <span>666</span>
    </div>
  </body>

2.子元素是块级元素

    <div class="container">
      <div class="inner"></div>
    </div>

(1).定位+margin,父相子绝

    <style>
      .container {
        position: relative;
        width: 100%;
        height: 1000px;
      }
      .inner{
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
        width: 100px;
        height: 100px;
        background-color: blue;
      }
    </style>

(2).定位+transform,父相子绝

    <style>
      .container {
        position: relative;
        width: 100%;
        height: 1000px;
      }
      .inner{
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100px;
        height: 100px;
        background-color: pink;
      }
    </style>

(3).flex布局

    <style>
      .container {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 1000px;
      }
      .inner{
        width: 100px;
        height: 100px;
        background-color: pink;
      }
    </style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值