常用布局:水平垂直居中 & 多列等高

535 阅读2分钟

水平居中布局

  • 固定一个宽度,然后添加 margin:0 auto 属性
div {
  width: 200px;
  margin: 0 auto;
}
  • 利用 inline-block + text-align: center 实现
.container {
  background: rgba(0, 0, 0, 0.5);
  text-align: center;
  font-size: 0;
}
.box {
  display: inline-block;
  width: 500px;
  height: 400px;
  background-color: pink;
}
<div class="container">
  <div class="box"></div>
</div>

水平垂直居中布局

宽高固定

  • 利用绝对定位,设置四个方向的值都为 0,并将 margin 设置为 auto,由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中。
div {
  position: absolute;
  width: 300px;
  height: 300px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
  • 利用绝对定位,先将元素的左上角通过 top:50%left:50% 定位到页面的中心,然后再通过 margin 负值来调整元素的中心点到页面的中心。
div {
  position: absolute;
  width: 300px;
  height: 300px;
  top: 50%;
  left: 50%;
  margin-top: -150px;
  margin-left: -150px;
}

不限宽高

绝对定位

利用绝对定位,先将元素的左上角通过 top:50%left:50% 定位到页面的中心,然后再通过转换属性 -- translate 来调整元素的中心点到页面的中心。

div {
  position: absolute;
  width: 300px;
  height: 300px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

flex 布局

使用 flex 布局,通过 align-items:centerjustify-content:center 设置容器内的子元素在垂直和水平方向上为居中分布。

.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div class="box"></div>
</div>

多列等高布局

01.png

多列布局中,列之间的高度不一样就会像上图一样参差不齐,影响整齐度。这里介绍最简单实用的方法 -- flex

flex

设置 item 在交叉轴上的布局方式为 stretch(拉伸为父元素的高度),就能实现多列等高效果:

.container {
  display: flex;
  align-items: stretch;
}
<div class="container">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

01.png