#div1{
width: 200px;
height: 200px;
background-color: #6699FF;
margin:auto;
position: absolute; //父元素需要相对定位
left: 0;
top: 0;
right: 0;
bottom: 0;
}
帮忙分析下这段代码是如何实现居中的,多谢。
通过
width
和height
限制大小,从而在父元素和子元素间留出空间;通过
position
,margin
和left
让子元素的外边距等分了留出的空间,从而达到居中的效果。
附上在 Firefox 中实测有效的代码:
<!-- index.html -->
<style>
#child {
width: 200px;
height: 200px;
background-color: #6699FF;
margin:auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
</style>
<div id="parent">
<div id="child"></div>
</div>