三种方法都比较容易理解,父元素设置属性都相同,都是父元素设置后,子元素定位后再做细微调整,但最终结果也都相同,实现了居中的目的。
1、子元素宽高比父元素小的情况下,使用定位方法居中
<style> 父元素{ width:400px; height:400px; border:1px solid #000; margin 100px auto 0; position:relative; } 子元素{ width:200px; height:100px; background:yellow; position:absolute; margin:auto; top:50%; left:50%; right:50%; bottom:50%; } </style>2、已知子元素宽高
父元素{ width:400px; height:400px; border:1px solid #000; margin 100px auto 0; position:relative; } 子元素{ width:200px; height:100px; background:yellow; position:absolute; margin:auto; top:50%; left:50%; margin-top:-50px;/*回高度的一半*/ margin-left:-100px;/*回宽度的一半*/ }3、固定定位后,使用transform偏移居中(css3技术,IE不支持) 父元素{
width:400px; height:400px; border:1px solid #000; margin 100px auto 0; position:relative; } 子元素{ width:200px; height:100px; background:yellow; position:absolute; margin:auto; top:50%; left:50%; transform:translate(-50%,-50%); /*回高度的一半和回宽度的一半*/ }