我不是问这个伎俩怎么办?我知道如何padding而不是margin到h1,或者clearfix到parent等等。
我只感兴趣的只是一件事:为什么h1的边缘推下身体,但不是按下。
body { position: relative; margin: 0; padding: 0; overflow: hidden; background-color: silver; } .absolute { position: absolute; top: 0; left: 0; width: 50px; height: 50px; background-color: darkblue; } .wrapper { position: relative; overflow:hidden; width: 50%; height: 200px; overflow: hidden; background-color: yellow; } .wrapper > .absolute { background-color: darkcyan; }
<div class="absolute"></div> <h1>Some title</h1> <div class="wrapper"> <div class="absolute"></div> <h1>Some title</h1> </div>
好的,我会尽量更清楚。如果您点击下面的链接,您可以看到我的JSFiddle。背景颜色:银色的身体标签。当我查看代码检查器时,由于h1的余量,我看到body标签开始略低。但背景颜色从顶部开始。这意味着代码检查员对我说谎,身体从顶部开始。那么为什么那么一个绝对定位的元素是身体的直接孩子不能从顶部开始?
解决方法
至于为什么银色背景超出身体元素,那就是by design:
3.11.1. The Canvas Background and the Root Element
The background of the root element becomes the background of the canvas and its background painting area extends to cover the entire canvas. However,any images are sized and positioned relative to the root element as if they were painted for that element alone. (In other words,the background positioning area is determined as for the root element.) The root element does not paint this background again,i.e.,the used value of its background is transparent.
3.11.2. The Canvas Background and the HTML <body> Element
For documents whose root element is an HTML
HTML
element or an XHTMLhtml
element: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’,user agents must instead propagate the computed values of the background properties from that element’s first HTMLBODY
or XHTMLbody
child element. The used values of that BODY element’s background properties are their initial values,and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for theBODY
element rather than theHTML
element.
根元素的默认背景颜色始终是透明的,因此在html元素上设置背景颜色可防止银色背景从身体元素中渗出(您会看到检查员其实不会对您说谎):
html { background-color: white; } body { position: relative; margin: 0; padding: 0; overflow: hidden; background-color: silver; } .absolute { position: absolute; top: 0; left: 0; width: 50px; height: 50px; background-color: darkblue; } .wrapper { position: relative; overflow:hidden; width: 50%; height: 200px; overflow: hidden; background-color: yellow; } .wrapper > .absolute { background-color: darkcyan; }
<div class="absolute"></div> <h1>Some title</h1> <div class="wrapper"> <div class="absolute"></div> <h1>Some title</h1> </div>