我总是看到这样的代码:
#container {
background:#000000 none repeat scroll 0 0;
display:block;
overflow:hidden;
position:relative;
width:100%;
}
我认为位置相对用于使用 CSS 属性左上右下 (px) 相对于其父元素容纳 div。像下面的例子那样单独使用它有什么意义?相对位置会影响哪些其他属性?
最佳答案
子元素位置会受此影响。
在将父元素位置设置为相对位置后,当我们尝试将子元素位置设置为绝对位置时,它只会相对于父元素而不是文档绝对放置。
第一个例子
<style>
#container
{
background:red none repeat scroll 0 0;
display:block;
position:relative;
top: 100px;
left: 100px;
width:100%;
}
#child
{
position: absolute;
top: 0px;
left: 0px;
}
</style>
<div id="container">
<div id="child">
I am absolutely placed relative to the container and not to the document
</div>
</div>
第二个例子
<style>
#container
{
background:red none repeat scroll 0 0;
display:block;
top: 100px;
left: 100px;
width:100%;
}
#child
{
position: absolute;
top: 0px;
left: 0px;
}
</style>
<div id="container">
<div id="child">
I am absolutely placed relative to the container and not to the document
</div>
</div>
试着检查上面的两个例子,你会发现不同之处。
关于css - 位置相关 DIVS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1938582/