css水平居中元素的宽度探究
小妮浅浅
2021-08-30 09:48:523899浏览 · 0收藏 · 0评论

水平居中还是比较容易的,先看子元素是固定宽度还是宽度未知。
1、固定宽度这种方式是绝对定位居中,除了使用margin,还可以使用transform。
(注意浏览器兼容性,只适用于 ie9+,移动开发请忽略)
.container{
width: 300px;
height: 200px;
background: pink;
position: relative;
}
.inner{
width: 100px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -50px;
background: #fff;
text-align: center;
}2、宽度未知将子元素设置为行内元素,然后父元素设置text-align: center。
.container{
width: 300px;
height: 200px;
background: pink;
position: relative;
text-align: center;
}
.inner{
display: inline-block;
}以上就是css水平居中元素的宽度探究,希望对大家有所帮助。更多css学习指路:css教程
本文教程操作环境:windows7系统、css3版,DELL G3电脑。
关注公众号,随时随地在线学习