三种方法都比较容易理解,父元素设置属性都相同,都是父元素设置后,子元素定位后再做细微调整,但最终结果也都相同,实现了居中的目的。
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%);
/*回高度的一半和回宽度的一半*/
}
本文详细介绍了CSS中实现元素居中的三种常见方法:1)通过相对定位和绝对定位结合,调整边距实现;2)已知子元素尺寸时,利用负margin调整;3)使用CSS3的transform属性进行偏移居中。这三种方法适用于不同场景,都能有效达到居中效果。
2049

被折叠的 条评论
为什么被折叠?



