div上相对位置的div

Sam*_*uel 5 html css position css-float

我不明白为什么浮动右或左的div不在具有相对位置的div之上或者在后面声明最后一个时用背景颜色定义.

这是html:

<html>
<body>
    <div class="container">
        Main container <br/><br/>

        <div class="header">This is the header</div>
        <div class="text-right">Right text</div>
        <div class="footer">This is the footer</div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

这是css:

.header {
    background-color:blue;
    border: solid;
    color: white;
    border-color:black;
    height: 100px;
}

.text-right{
    float: right;   
    border: solid;
    background-color: green;
}

.container{
    padding: 10px;  
    border: solid;
}

.footer{
    padding-top: 50px;
    border: solid;
    background-color: yellow;
    position: relative;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用.clear:这两个规则来纠正这个问题,但我的主要观点是:为什么当我在.footer规则中设置背景颜色或位置或两者时,浮点数在页脚下?

非常感谢你!

Sam*_*uel 6

在阅读这篇非常好的帖子时,在帖子的最后,作者谈到了z-order内部工作,但也说如果你想了解更多,下一篇文章将是一篇更详细的文章

关键点在于z轴中的顺序放置元素.

这是作者所说的:

如果我们不指定任何z-index值,则从最靠近用户到最远的默认堆叠顺序如下:

1. Positioned elements, in order of appearance in source code
2. Inline elements
3. Non-positioned floating elements, in order of appearance in source code
4. All non-positioned, non-floating, block elements in order of source code
5. Root element backgrounds and borders
Run Code Online (Sandbox Code Playgroud)

如我们所见,定位元件(1)总是位于未定位元件(3-4)的顶部.如果我div只使用float属性,则此元素将不会"定位"到表面上.

在这种情况下,div使用相对属性值定位的第二个元素(我的页脚)将位于前一个元素的顶部,而不仅仅是我不在clear: both属性之后添加属性,float div或者因为在浮动之后添加了最后一个属性元素,但因为它的位置!

就像powerbuoy所说的那样,你必须设置相对于float元素添加一个位置才能够在浮动元素的堆栈顶部.但这还不够.因为这两个元素现在处于同一级别并且因为它们彼此交叉,所以必须告诉引擎哪一个将是第一个,这就是为什么你必须再次将z-order设置为浮动元素的PowerBuoy.

我不是一个非常优秀的作家,因此我强烈建议你阅读我之前提到过的引用文章.我想你会对案件有一个非常深刻的解释.