今天文汇建站公司的小编给大家带来两种元素居中的方式,可根据网站的具体情况进行选择使用。
一、已知宽度的元素居中
思路:居中元素父级设置相对定位,居中元素绝对定位,距离顶部 top:50%,左边left:50%,通过margin-top、margin-left等于负的居中元素宽高的一半。
.box{position:relative;width:200px;height:300px;}
.a{position:absolute;top:50%;left:50%;margin-top:-150px;margin-left:-100px;}
二、未知宽度的元素居中
思路:居中元素父级设置相对定位,居中元素绝对定位,距离顶部 top:50%,左边left:50%,然后使用css3 transform:translate(-50%; -50%)使元素居中。
.box{position:relative;width:200px;height:300px;}
.a{position:absolute;top:50%;left:50%;margin-top:-150px;transform:translate(-50%; -50%);}
虽然第二种方式更为便捷简单,但IE9以下不支持transform属性。
上一篇: 2018年网站设计风格的流行趋势
下一篇: H标签如何在网站中正确使用