首页 > 技术文章 > css 垂直水平居中

xi-li 2019-06-19 15:54 原文

原文地址:https://www.cnblogs.com/cme-kai/p/6192544.html

一、固定宽高

1、父元素固定宽高+定位 + margin:auto(缺点:不支持IE7及以下的浏览器

html代码:

<div>
    <img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4177665583,3954494687&fm=26&gp=0.jpg" alt="">
</div>

css代码:

div{
      width: 600px;
      height: 500px;
      position: relative;
      border: 1px solid #465468;
 }
 img{
      position: absolute;
      margin: auto;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
 }

2、子元素固定宽高+定位 + margin-top + margin-left(兼容性好

html代码:

<div class="container">
    <div class="inner"></div>
</div>

css代码: 

.container{
  width: 500px;
  height: 400px;
  border: 1px solid #379;
  position: relative;
} .inner{   width: 400px;   height: 300px;   background-color: #5eccb1;   position: absolute;   top: 50%;   left: 50%;   margin-top: -150px; /*height的一半*/   margin-left: -200px; /*width的一半*/ }

二、不固定宽高

1、定位 +transform缺点:不支持IE8及以下的浏览器

html代码:

<div>
<img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4177665583,3954494687&fm=26&gp=0.jpg" alt="">
</div>

css代码: 

div{
width: 600px;
height: 500px;
position: relative;
border: 1px solid #465468;
}
img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}

2、flex弹性盒子法(缺点:不支持IE9及以下浏览器

html代码:

<div>
<img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4177665583,3954494687&fm=26&gp=0.jpg" alt="">
</div>

css代码: 

div{
  display: flex;
  align-items: center;
  justify-content: center;
}

3、table-cell法缺点:不支持IE7及以下浏览器

html代码:

<div>
<img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4177665583,3954494687&fm=26&gp=0.jpg" alt="">
</div>

 css代码:

div{
width: 600px;
height: 500px;
display: table-cell;
vertical-align: middle;
text-align: center;
border: 1px solid #465468;
}
img{
vertical-align: middle;
}

推荐阅读