CSS居中汇总

行内元素

1.水平局中

text-align:center;

2.水平居中

width:fit-content;
// 此时父元素宽度适应子元素宽度

// 再给父元素添加
margin:auto;

3.垂直居中

line-height:父元素高度;

// 只能用于单行文本

块级元素

水平居中

// 给子元素
margin:0 auto;

水平垂直居中

1.

.father{
  position: relative;
}

.son{
  position:absolute;
  left: calc(50% - 子元素自身一半宽);
  top: calc(50% - 子元素自身一半高);
}

2.

.father{
  position: relative;
}

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

3.

.father{
  position: relative;
}

.son{
  position:absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

/* 原理:
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  子元素会填充父元素剩余空间
  有了可分配的空间再margin: auto;即可水平垂直居中
*/

4.

// 不给父元素宽高,给子元素宽高

// 接着给父元素padding实现居中效果

5.

.father{
  display: flex;
  align-items: center;    // 垂直居中
  justify-content: center;    // 水平居中
}

6.

.father {
  text-align: center;    // 水平居中
}
.son {
  display: inline-block;    // 水平居中
  vertical-align: middle;
}

// 垂直居中
.father::before {
  content: "";
  width: 0;
  height: 父元素高度;
  display: inline-block;
  vertical-align: middle;
}

7.

.son {
  padding: calc((100% - 子元素自身高度) / 2);
  // 此时子元素大小和父元素一样,产生了一个覆盖效果,看不到父元素了
  // 让背景颜色只对content生效,不对padding生效
  background-clip: content-box;
}

猜你喜欢

转载自blog.csdn.net/weixin_63836026/article/details/125036110