我已经将这个css应用于我的html文档:
html {
background-color: red;
}
body {
background-color: yellow;
}
并且页面的背景变为红色而不是黄色。body位于html之后,因此它必须覆盖html的红色。为什么没有发生?提前谢谢。
因为你的身体是空的(0px高度)
如果我们改变机身的h/w,你会得到这个(包括可以重置的边距/填充)
html {
background-color: red;
}
body {
background-color: yellow;
width: 100vw;
height: 100vh;
}
带内容:
html {
background-color: red;
}
body {
background-color: yellow;
}
<h1>Body no longer empty</h1>
HTML和BODY元素是不同的元素,因此级联规则(包括您放置规则集的顺序)在这里不相关。
您的困惑可能源于CSS对HTML和BODY元素有一些特殊规则:
对于根元素为HTML的文档;HTML";元素或XHTML";html";元素的计算值"transparent"表示"background color","none"表示"background image",则用户代理必须使用该元素的第一个HTML"中后台属性的计算值;BODY";元素或XHTML";身体;元素的子元素,并且不能为该子元素绘制背景。
因此,如果您只设置其中的一个,那么这就是您将获得的颜色。
这里有一个红色的HTML元素。
html { background: red; }
这里有一个黄色的HTML元素,因为它从BODY元素中提取了颜色。
body { background: yellow; }
但是,由于您同时设置了和,因此这些特殊规则不适用。
HTML元素被设置为红色,BODY元素被设置为黄色。
你就是看不到它,因为你的身体元素没有内容,所以计算得到的高度为零。
html { background: red; }
body { background: yellow; }
<p>Hello, world.
<p>Since there is content in the body, it no longer has a zero height, so you can see its background.