为什么给 html/body 添加背景色会影响整个浏览器界面背景色?

作者站长头像
站长
· 阅读数 11

一般情况下,我们使用 css 控制的最高节点就是 body,在给 body 提供背景色的时候会使整个浏览器背景色变为 body 的背景色,即使 body 的宽高并不足以铺满浏览器视窗。但这个时候我们再为 html 设置背景色,那么整个浏览器的背景色就会从 body 的背景色值变为现在给 html 设置的背景色值。那么为什么会造成这样的情况呢?

以下是几个示例:

示例一:body设置background颜色边框和边距后的表现

body{background:#069; margin:100px; border:30px solid #093;}

为什么给 html/body 添加背景色会影响整个浏览器界面背景色?

示例二:再给html标签设置背景色后的样式表现

html{background:#999;}
body{background:#069; margin:100px; border:30px solid #093;}

为什么给 html/body 添加背景色会影响整个浏览器界面背景色?

回复
1个回答
avatar
test
2024-07-11

https://w3c.github.io/csswg-d...

For documents whose root element is an HTML HTML element or an XHTML html element [HTML]: 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 HTML BODY or XHTML body 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 the BODY element rather than the HTML element.
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容