CSS实现水平垂直居中的方式有哪些?

x33g5p2x  于2022-02-20 转载在 CSS3  
字(1.7k)|赞(0)|评价(0)|浏览(785)

CSS实现水平垂直居中的方式有哪些?

基本结构样式:

.box {
  width: 400px;
  height: 400px;
  background-color: red;
}

.inner {
  width: 100px;
  height: 100px;
  background-color: blue;
}
<div class="box">
  <div class="inner"></div>
</div>

1.利用flex布局

将父元素启动flex布局,并设置justify-content: center; align-items: center;

添加样式:

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

2.利用flex+margin

父元素设置display: flex;,子元素设置margin: auto;

添加样式:

.box { display: flex; }
.inner { margin: auto; }

3.利用定位,子绝父相

3.1.利用margin: auto(偏移量都为0)

将子元素的top、left、right、bottom都设置为0,再设置其margin为auto即可。

添加样式:

.box { position: relative; }

.inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
3.2.利用平移translate

先设置子元素的top和left都为50%,即父元素宽高的一半,再使用translate往回走自己宽高的一半。

添加样式:

.box { position: relative; }

.inner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

4.知道具体宽高,通过计算

4.1.子绝父相,直接计算或者使用calc()

添加样式:

.box { position: relative; }

.inner {
  position: absolute;
  /* 直接计算 */
  /* top: 150px;
  left: 150px; */
  top: calc(50% - 50px);/* 使用calc() */
  left: calc(50% - 50px);
}
4.2.利用margin

子元素设置margin-top;但是存在父子共用外边距问题,父元素需要设置overflow: hidden;

添加样式:

.box { overflow: hidden; }

.inner {
  margin: 0 auto;
  margin-top: 150px;
}
4.3.利用padding

父元素设置padding,防止父盒子被撑大,需加上box-sizing: border-box;

添加样式:

.box {
  box-sizing: border-box;
  padding: 150px;
}

5.利用display的table-cell属性值

5.1.利用display+vertical-align

父元素设置display: table-cell;vertical-align: middle;,子元素设置margin: 0 auto;

添加样式:

.box {
  display: table-cell;
  vertical-align: middle;
}

.inner { margin: 0 auto; }
5.2.利用display+vertical-align+text-align

父元素设置display: table-cell以及内容的水平和垂直居中,注意子元素要设置为行内块。

添加样式:

.box {
  display: table-cell; /* 此元素会作为一个表格单元格显示 */
  vertical-align: middle; /* 把此元素放置在父元素的中部 */
  text-align: center;
}

.inner { display: inline-block; }

6.以上方法最终运行结果

相关文章