美文网首页
2020-03-05 CSS水平垂直居中学

2020-03-05 CSS水平垂直居中学

作者: 严萨满 | 来源:发表于2020-03-05 13:08 被阅读0次

1.块级元素水平居中,水平元素垂直居中

<div class="wrap">
  <div class="example1">
    <p>CSS</p>
  </div>
</div>
.example1 p {
  width: 100px;
  height: 100px;
  background-color: red;
  margin: 0 auto; /*块级元素水平居中*/
  line-height: 100px;/* 内联元素垂直居中*/
  text-align: center; /* 内联元素水平居中 */
}

CodePen:CSS块级水平居中

2.块级元素垂直居中

<div class="wrap">
  <div class="example2">
    <p>CSS</p>
  </div>
</div>
.wrap {
  position: relative;
  background-color: orange;
  width: 300px;
  height: 300px;
}
.example2 {
  background-color: red;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 50%;
  top: 50%;
  /*margin: -50px 0 0 -50px; 已知高度宽度*/
  transform: translate(-50%,-50%);/*未知高度宽度*/
}

CodePen:CSS块级垂直居中

3.flex布局

<div class="wrap">
  <div class="example3">
    <p>CSS</p>
  </div>
</div>
.wrap{
  background-color: #ff8c00;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center; /*使子项目水平居中*/
  align-items: center; /*使子项目垂直居中*/
}
.example3 {
  background-color: #f00;
  width: 100px;
  height: 100px;
}

CodePen:Flex布局

相关文章

网友评论

      本文标题:2020-03-05 CSS水平垂直居中学

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