DIV的常用的几种绝对居中方法
方法一:利用margin和绝对定位一
优点:
1.支持跨浏览器,包括IE8-IE10
缺点:
1.必须声明宽高度。
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.container .box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: skyblue;
}
方法二:利用margin和绝对定位二
优点:
1.支持跨浏览器,包括IE8-IE10
缺点:
1.必须声明宽高度。
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.container .box {
position: absolute;
left: 50%;
top: 50%;
margin: -50px;
width: 100px;
height: 100px;
background-color: skyblue;
}
方法三:利用flex弹性布局
优点:
1.弹性布局,对宽高无既定要求
缺点:
1.有兼容性问题(IE11+才支持)。
<div class="container">
<div class="box"></div>
</div>
.container {
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
width: 200px;
height: 200px;
background-color: pink;
}
.container .box {
width: 100px;
height: 100px;
background-color: skyblue;
}
方法四:利用CSS3新特性transform
优点:
1.弹性布局,对宽高无既定要求
<div class="container">
<div class="box"></div>
</div>
.container {
position: relative;
width: 200px;
height: 200px;
background-color: pink;
}
.container .box {
position: absolute;
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: skyblue;
transform: translate(-50%, -50%);
}
缺点:
1.有兼容性问题(IE10+才支持)。
总结:
对于宽高固定的元素:
1.使用第一、第二种方法
对于宽高不固定的元素:
1.使用第三、第四种方法