html - Canvas 背景和 HTML <body> 元素

标签 html css background specifications

根据spec :

It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

但是并没有说它有什么优势。为什么规范推荐这个?

附言当我看到 Extra scrollbar when body height is 100vh 时,我想到了: 将背景简单地提供给 html 元素不是更好吗?

最佳答案

在 CSS 之前,通过将 backgroundbgcolor 属性添加到 HTML 中的 body 元素来指定背景(以及类似的text, link, alink, vlink, leftmargin, marginwidthtopmarginmarginheight)。

CSS 兼容的浏览器将这些表示属性转换为适当的样式规则,作为作者级别的表示提示放置,其优先级低于作者级别的 * 规则。有关更多信息,请参见 css-cascade-3HTML .即,backgroundbgcolor 属性分别转换为 background-imagebackground-color 声明,用于body 元素。

因此,建议作者为 body 元素而不是 html 元素指定 Canvas 背景是为了简化遗留 HTML 文档从展示属性的迁移body 元素到 CSS。通常,如果您同时控制了标记和 CSS,那么您可能想要做的第一件事就是摆脱表示属性。但是您不必立即这样做;您可以只添加一个 background 特定于 body 元素的声明,它将无缝替换整个页面背景(如问题中的规范链接中所述)表示属性,无需进一步操作:

/* The bgcolor attribute is equivalent to a

body {
  background-color: #FFFFFF;
}

rule at this position in the stylesheet,
except with less precedence than a * rule.
The following rule will override it as a
normal part of the cascade. */

body {
  background-color: yellow;
}
<body bgcolor=#FFFFFF>
  <h1>Hello world!</h1>
  <p>This page was once white...
  <p>... now it's yellow!

如果您将它添加到 html 元素,您将得到两个背景:

/*
body {
  background-color: #FFFFFF;
}
*/

html {
  background-color: yellow;
}
<body bgcolor=#FFFFFF>
  <h1>Hello world!</h1>
  <p>This page was once white...
  <p>... wait, what?

如果您知道 body 元素具有 bgcolor 属性,这确实具有视觉提醒您摆脱该属性的优势.但是,如果您没有立即想到这一点,您可能会被留下 flummoxed .

当然,如果您要编写新文档,那么这就变成了传统问题(这与整个“易于迁移”相关)。没有什么可以阻止您将背景应用到 both htmlbody 以获得有趣的效果,尽管即使这样在很大程度上已被添加多个的能力所取代背景层到一个元素,只有在需要支持旧浏览器时才是真正必要的。上面的链接中有更多相关信息。

关于html - Canvas 背景和 HTML <body> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992360/

相关文章:

ios - 在后台状态卡住http请求

javascript - 如何获取innerHTML的css类?

css - 用 css 2d 矩阵移动东西

jquery - 老问题 : how to make jQuery Mobile Page cover the full screen height only when screenHeight is greater than page height

java - 背景变化导致强制关闭

html - YOUTUBE 播放器背景图片

javascript - 用javascript重复一个div?

javascript - 导航栏不再滚动到页面上的部分?

html - 在 VB 6.0 中将 HTML 文件附加为电子邮件

javascript - 第二个背景图像的不同动画行为