实现盒子居中的若干方法

2022 年 5 月 10 日 星期二
/
15

实现盒子居中的若干方法

盒子宽高已知

  • 使用绝对定位将top left 都设为50%,并减去盒子一般宽高,盒子将居中显示。
.box {
  height: 200px;
  width: 200px;
  background-color: black;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -100px;
}
<div class="box"></div>

盒子宽高未知

  • 使用绝对定位将top left right bottom 都设为0,盒子将居中显示。
.box {
  height: 200px;
  width: 200px;
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
<div class="box"></div>
  • 使用绝对定位将top left 都设为50%,并使用transform:translate(-50%,-50%)将盒子移动自身50%,盒子将居中显示。
.box {
   height: 200px;
   width: 200px;
   background-color: black;
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
 }
<div class="box"></div>
  • 使用flex布局。
  .body {
    display: flex;
  }
.box {
  height: 200px;
  width: 200px;
  background-color: black;
  justify-content: center;
  align-items: center;
}
<div class="box"></div>
  • flex布局变种,垂直居中使用marin:auto 0;代替,此方法可以使该盒子内部的文本在居中的同时保持开头在盒子中显示。 css .body { display: flex; } .box { height: 200px; width: 200px; background-color: black; justify-content: center; margin: auto 0; }
<div class="box"></div>
  • element-ui源码中发现的,父盒子使用text-align:center让子盒子水平居中,子盒子使用vertical-align: middle垂直居中,vertical-align这个属性,这个属性虽然是垂直置中,不过却是指在元素内的所有元素垂直位置互相置中,并不是相对于外框的高度垂直居中。所以需要设其中一个子盒子高度100%,这样其中所有元素都相对于这个元素做到真正居中。
  .box {
  height: 500px;
  width: 500px;
  background-color: black;
  text-align: center;
}
.child-box {
  display: inline-block;
  vertical-align: middle;
  height: 200px;
  width: 200px;
  background-color: #ffffff;
}
.box::after {
  content: '';
  height: 100%;
  vertical-align: middle;
  display: inline-block;
}
    <div class="box">
  <div class="child-box"></div>
</div>
  • display:table-cell让标签元素以表格单元格的形式呈现,类似于td标签,设置了display:table-cell的元素对宽度高度敏感,对margin值无反应,响应padding属性,父盒子使用该属性后设置vertical-align: middle;可使子盒子垂直居中,使用text-align: center;可使子盒子水平居中。对于table-cell的具体应用,参考网址
  .container {
  display: table-cell;
  width: 1000px;
  height: 500px;
  background-color: #beceeb;
  font-size: 144px;
  text-align: center;
  vertical-align: middle;
}
.container .children {
  display: inline-block;
  width: 500px;
  height: 250px;
  background-color: #fff;
  vertical-align: middle;
}
<div class="container">
     <div class="children"></div>
   </div>

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...