(前端)面试300问之(2)CSS元素居中【水平、垂直、2者同时居中】

188 阅读4分钟

一、仅水平居中

1、行内元素

1)给父元素添加 text-align:center 即可

<div class="parent">
  <span class="child">我是子元素</span>
</div>

.parent {
  width200px;
  background-color: red;
  text-align: center;
}
.child {
  background-color: green;
}

效果:

2)父元素添加 width:fit-content; 和 margin:auto 。

DOM结构不变。

.parent {
  width: fit-content;
  margin: auto;
  background-color: red;
}
.child {
  background-color: green;
}

效果:

2、块级元素

1)子元素加 margin:0 auto

<div class="parent">
  <div class="child">我是子元素</div>
</div>

.parent {
  background-color: red;
}
.child {
  margin0 auto;
  background-color: green;
  width100px;
  text-align: center;
}

效果:

二、仅垂直居中

1、行内元素

1)line-height与height值保持一致即可【仅对单行文本生效】。

.parent {
  background-color: red;
  height200px;
  line-height200px;
}
.child {
  background-color: green;
}

效果:

三、水平、垂直均居中

1、块级元素

1)"子绝【绝对absolute】父相【相对relative】"。 条件:必须知道 子元素的宽、高。

<div class="parent">
  <div class="child">我是子元素</div>
</div>
【Tip:以下均是这个DOM结构】

.parent {
  background-color: red;
  width200px;
  height300px;
  position: relative;
}
.child {
  background-color: green;
  width100px;
  height200px;
  position: absolute;
  /* 50%是基于父元素的 高度,100px是 子元素高度 的一半 */
  topcalc(50% - 100px);
  /* 50%是基于父元素的 宽度,50px是 子元素宽度 的一半 */
  leftcalc(50% - 50px);
}

效果:

2)定位 + transform 。

.parent {
  background-color: red;
  width200px;
  height300px;
  position: relative;
}
.child {
  background-color: green;
  position: absolute;
  /* 下面2个50%,使得子元素的左上角点在父元素的正中心了 */
  top50%;
  left50%;
  /* 下面2个-50%【分别以子元素的宽、高为基准】,平移后便在父元素的正中间了 */
  transformtranslate(-50%, -50%);
}

效果:

3)定位 + margin 。

.parent {
  background-color: red;
  width200px;
  height300px;
  position: relative;
}
.child {
  background-color: green;
  /* 这里的 width、height 要设值,不然子元素可能会填满父元素 */
  width100px;
  height200px;
  /* 原理:子元素就会填充父元素的所有可用空间,所以,在水平垂直方向上,就有了可分配的空间 */
  position: absolute;
  top0;
  bottom0;
  left0;
  right0;
  margin: auto;
}

效果:

若子元素的宽、高都注释掉,效果就不明显了,子元素会充满父元素:

4)父元素设置 padding 值。

.parent {
  background-color: red;
  padding10px 20px;
}
.child {
  background-color: green;
}

效果:

5)父元素 display:flex 。

.parent {
  background-color: red;
  width200px;
  height300px;
  display: flex;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
}
.child {
  background-color: green;
}

效果:

6)父元素为 table-cell 布局。

<div class="parent">
  <!-- spandiv效果明显 -->
  <span class="child">我是子元素</span>
</div>

.parent {
  background-color: red;
  width200px;
  height300px;
  /* display: table-cell 将parent模拟成一个表格单元格【td标签】 */
  display: table-cell;
  /* 水平居中 */
  text-align: center;
  /* 垂直居中 */
  vertical-align: middle;
}
.child {
  background-color: green;
}

7)其他的也可以实现,但是可能适用性、理解难度较大,所以暂时不列出~

总结

1)思维导图【方便记忆~】:

本文章只是简单说了实操部分, 它们更深入的原理没有讲解, 大家感兴趣的话可以自己私底下去搜索相关资料 或 底下评论与交流~