blog icon indicating copy to clipboard operation
blog copied to clipboard

水平垂直居中的五种方式

Open wuxianqiang opened this issue 4 years ago • 0 comments

法一 绝对定位与负边距实现 利用绝对定位,将元素的top和left属性都设为50%,再利用margin边距,将元素回拉它本身高宽的一半,实现垂直居中。 法二 绝对定位与margin

  <style>
    .wrapper {
      width: 100%;
      height: 500px;
      background: pink;
      position: relative;
    }
    .box {
      width: 20px;
      height: 20px;
      background: red;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
      margin: auto;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="box"></div>
  </div>
</body>

总结:默认设置margin:auto可以让块级元素水平居中,auto 默认只会计算左右边距。而上下如果设置为auto时默认是取0.也就是说,margin:auto和margin:0 auto 在一般情况下没有区别,不能实现垂直居中。

但是有了绝对定位后,margin-top和margin-bottom 的值就不是0了,也是通过计算所得。所以能实现垂直居中。

法三 Css3显威力 利用Css3的transform,可以轻松的在未知元素的高宽的情况下实现元素的垂直居中。

法四. flex布局轻松解决

如果非要写五种,那么可以试试下面不常用的方法:

  <style>
    .wrapper {
      width: 500px;
      height: 500px;
      background: pink;
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }
    .box {
      width: 20px;
      height: 20px;
      background: red;
      display: inline-block;
    }
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="box"></div>
  </div>
</body>

display: table-cell;和vertical-align: middle;可以垂直居中,text-align: center;进行水平居中

wuxianqiang avatar Apr 29 '20 07:04 wuxianqiang