美文网首页
CSS(五)对齐方式(居中)

CSS(五)对齐方式(居中)

作者: fanren | 来源:发表于2021-03-02 11:21 被阅读0次

一、水平居中

  • margin: auto;设置子容器margin属性,可使元素在父容器内水平居中
<div class="bg">
    <div class="content"></div>
</div>
...
.bg {
  background-color: gray;
  width: 500px;
  height: 100px;
}
.content {
  background-color: red;
  width: 100px; 
  height: 50px;
  margin: auto;
}
效果图

二、垂直居中

  • line-height:设置父容器的line-heightheight属性,可使容器内部的元素垂直居中;
  <div class="bg">
    <div class="content">aaaa</div>
  </div>
...
.bg {
  background-color: gray;
  width: 500px;
  height: 100px;
  line-height: 100px; // 这里 line-height与height高度一致
}
.content {
  background-color: red;
  width: 100px; // content不能设置高度
}

line-height是设置在父容器内,使容器内部子元素垂直居中;

  • padding:设置父容器的padding与子元素的高度,会自动计算出父容器的高度,并在子元素会垂直居中在父容器内;
  <div class="bg">
    <div class="content"></div>
  </div>
...
.bg {
  background-color: gray;
  width: 500px;
  padding: 25px; // 设置padding,但是不要设置高度
}
.content {
  background-color: red;
  width: 100px;
  height: 50px; // 设置高度
}
截图
  • transform:设置子元素的transform可实现垂直居中
  <div class="bg">
    <div class="content"></div>
  </div>
...
.bg {
  background-color: gray;
  width: 500px;
  height: 100px;
}
.content {
  background-color: red;
  width: 100px;
  height: 50px;
  transform: translate(0, 50%);  // 垂直居中
}

相关文章

网友评论

      本文标题:CSS(五)对齐方式(居中)

      本文链接:https://www.haomeiwen.com/subject/pchgfltx.html