css水平居中 垂直居中 水平垂直居中

6,356 阅读2分钟

blog.csdn.net/freshlover/…

水平居中

  • 行内元素:text-align:center;
  • flex布局:display:flex; justify-content:center;
  • 常用(前提:已设置width值):margin-left:auto; margin-right:auto; margin:0 auto;
  • 不定宽块状元素水平居中:改变块状元素的 dispaly 属性为 inline, 然后给父级设置 text-aline:center 来实现水平居中, 这种方法的缺点是不能再给元素设置宽高了
<div style="text-align: center;">
      <div style="display: inline;">不定宽块状元素水平居中</div>        
</div>

垂直居中

  • 行高:height:100px;line-height:100px;
  • table-cell:

html

<div class="box box1">
       <span>垂直居中</span>
</div>

css

.box1{
   display: table-cell;
   vertical-align: middle;
   text-align: center;        
}
  • flex布局:display: flex; justify-content:center; align-items:center;

水平垂直居中

  • 方案1:position 元素已知宽度 父元素设置为:position: relative; 子元素设置为:position: absolute;距上50%,据左50%,然后减去元素自身宽度的距离就可以实现

html

<div class="box">
   <div class="content">
   </div>
</div>

css


.box {
   background-color: #FF8C00;
   width: 300px;
   height: 300px;
   position: relative;
}
.content {
   background-color: #F00;
   width: 100px;
   height: 100px;
   position: absolute;
   left: 50%;
   top: 50%;
   margin: -50px 0 0 -50px;
}
  • 方案2 如果元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);

  • 方案3 flex布局:display: flex; justify-content:center; align-items:center;

  • 方案4 不知道自己高度和父容器高度的情况下, 利用绝对定位只需要以下三行:

css

parentElement{
       position:relative;
   }

childElement{
       position: absolute;
       top: 50%;
       transform: translateY(-50%);

}

  • 若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可

css

parentElement{
       height:xxx;
   }

   .childElement {
     position: relative;
     top: 50%;
     transform: translateY(-50%);
   }