考虑以下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML</title>
<meta charset="utf-8" />
<style type="text/css">
h1 {
font-size: 2em;
font-family: Verdana;
font-weight: bold;
}
p {
border: 3px solid blue;
margin-top: -50px;
background-color: green;
color: white;
}
</style>
</head>
<body>
<h1>QUESTION</h1>
<p>The header text in the preceding h1 element is behind this
paragraph's text (as expected), but on top of this paragraph's
background and border (not expected).
</p>
</body>
</html>
请参阅此处的示例:http://jsfiddle.net/ZKHc9/ http://jsfiddle.net/ZKHc9/
为什么段落的背景和边框不像内容那样呈现在标题顶部?
因为这两个元素分别是同一堆栈上下文中的流内、非定位、块级元素.
两个流入的、非定位的块并不严格地彼此“上方”或“下方”——它们的内容和背景分别堆叠.
Adding position: relative
将使一个元素定位(与z-index: auto
)并将其放置在同一堆叠上下文中的非定位元素之上:它将在下面的绘制算法中的第 8 步进行渲染。
如果您阅读了 CSS2 规范Stacking Context 的详细描述 http://www.w3.org/TR/CSS2/zindex.html仔细观察,你会发现这是正确的行为。
同一堆栈上下文中的流内、非定位、块级元素首先渲染其所有背景,然后渲染其所有内容。他们的背景位于带有负数的定位元素上方z-index
并低于其他一切。
绘画算法中的相关步骤:
- ...
- ...
- ...
- For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:
- 元素的背景颜色。
- 元素的背景图像。
- 元素的边框。
- ...
- ...
- ... for all its in-flow, non-positioned, block-level descendants in tree order:
- ...
- ... for each line box of that element:
- For each box that is a child of that element, in that line box, in tree order:
- ...
- ...
- ...
- For inline elements:
- For all the element's in-flow, non-positioned, inline-level children
that are in this line box, and all runs of text inside the element that is on this line
box, in tree order:
- If this is a run of text, then:
- ...
- ...
- 文本。
- ...
- ...
- ...
- ...
浮动和定位元素始终是“原子的”——它们的背景和内容将在一个步骤(步骤 3、5、8 或 9)中一起渲染。但是,同一堆叠上下文中的流内非定位块元素将渲染其所有背景(在步骤 4 中),然后渲染其所有内容(在步骤 7 中)。
在这种情况下,对于流内、非定位同级元素 H1 和 P(树中 H1 在 P 之前),步骤 4 渲染 H1 背景,然后渲染 P 背景,然后步骤 7 渲染 H1 内容,然后渲染 P 内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)