<!DOCTYPE html>
...
<style scoped>
/* css */
</style>
w3.org 验证器给我这个错误:
Line 883, Column 17: Element style not allowed as child of element body in this context.
(Suppressing further errors from this subtree.)
<style scoped>...
Contexts in which element style may be used:
If the scoped attribute is absent: where metadata content is expected.
If the scoped attribute is absent: in a noscript element that is a child of a head element.
If the scoped attribute is present: where flow content is expected, but before any other flow content other than inter-element whitespace and style elements, and not as the child of an element whose content model is transparent.
Content model for element body:
Flow content.
据我了解,“scoped”属性可以让样式标签位于文档头部之外。那么为什么验证者对此不满意呢?
(我使用的是 Wordpress,这段代码是由一个插件生成的,这就是为什么我不能把它放在头部的原因。)
编辑: 这不验证 -
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<script type="text/javascript"></script>
<style scoped></style>
</body>
</html>
但如果 script 标签位于 style 标签之后,它就会这样做。这是什么原因?
最佳答案
W3C Markup Validator 在充当 HTML5 检查器时,根据 HTML 5.1 Nightly 等各种草案处理此问题。 ,现在表示 style
元素可能只出现在 head
元素内,除非存在 scoped
属性,在这种情况下它可能出现“在预期流动内容的地方,但在除元素间空白和样式元素之外的任何其他流动内容之前,而不是作为内容模型透明的元素的子元素”。在您的实际示例中,该元素出现在 script
元素之后(计为流内容)。因此,根据给定的定义,更改元素的顺序会将语法更改为有效。
或者,您可以将 style
元素包装在 div
元素中:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<script type="text/javascript"></script>
<div>
<style scoped></style>
</div>
</body>
</html>
根据 W3C Recommendation HTML5,scoped
属性根本无效.它出现在 HTML5 草案中,但由于缺乏实现而从建议中删除,但它仍处于“标准化轨道”中,可能会进入 HTML 5.1。
请注意,现有的浏览器通常会忽略 scoped
属性并允许 style
元素几乎在任何地方并将其内容应用于整个 HTML 文档(甚至是 之前的部分>style
元素)。
关于html - 在此上下文中元素样式不允许作为元素主体的子元素(<style scoped> 未验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27539084/