css样式——完美解决div水平居中及div水平垂直居中的方法总结
在我们网页开布局中,经常遇到div元素的垂直居中或者水平居中。这篇文章总结一下使用的方法。
div水平居中
1.通过margin:auto的方式
.div{
margin:auto;
width:60%;
}2.通过text-align的方式
.boxdiv{
text-align:center;
}
.boxdiv .div{
display:inline-block;
}3.通过定位的方式
.div{
position: absolute;
width: 100px;
left: 50%;
margin-left: -50px;/*宽度值/2*/
}div垂直水平居中
1.通过table-cell(vertical-align的百分比值是相对于line-height计算的)
.boxdiv{
width:400px;
height:400px;
display:table-cell;
vertical-align:middle;
text-align: center;
}
.boxdiv .div{
width:200px;
height:200px;
display:inline-block;
}2..绝对定位方式+四个方向置0(需设置子元素宽高,否则子元素将与父元素宽高一致)
.boxdiv{
width:400px;
height:400px;
position:relative;
}
.boxdiv .div{
width:200px;
height:200px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}3.通过定位+maring偏移
.boxdiv{
width:400px;
height:400px;
position:relative;
}
.boxdiv .div{
width:300px;
height:200px;
margin:auto;
position:absolute;
left:50%;
top:50%;
margin-left: -150px;
margin-top:-100px;
}4.通过css3的flex(存在兼容性问题,适合移动端)
.divbox{
width:400px;
height:400px;
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
}
.divbox .div{
width:200px;
height:200px;
background-color: red;
}5.absolute+transform
<div class="parent">
<div class="child">Demo</div>
</div>
<style>
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>6.box-alignandbox-pack 属性(IE不支持)
.parent{
position: relative;
top: 0; left: 0; right: 0; bottom: 0;
display: -webkit-box;
-webkit-box-align: center;
-webkit-box-pack: center;
}
.child{
-webkit-box-flex: 0;
}div的水平和垂直居中方法总结基本就这些了。如果你有更好的,或者更巧妙的解决方案,欢迎留言~~~~
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!