在此上下文中不允许元素样式作为元素主体的子元素(<style scoped> not validating)

mik*_*eck 13 html css w3c-validation

<!DOCTYPE html>
...
<style scoped>
/* css */
</style>
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

我的理解是'scoped'属性使得样式标记可以在文档的头部之外.那么为什么验证者不满意呢?

(我正在使用Wordpress,这个代码是由插件生成的,这就是为什么我不能把它放在头脑中.)

编辑:这不验证 -

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<script type="text/javascript"></script>
<style scoped></style>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但是如果脚本标记在样式标记之后,它就会发生.这是什么原因?

Juk*_*ela 16

W3C标记验证器在作为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>
Run Code Online (Sandbox Code Playgroud)

scoped根据W3C Recommendation HTML5,该属性完全无效.它存在于HTML5草案中,但由于缺乏实现而被从建议书中删除,但它仍处于"标准化轨道"中,可能会进入HTML 5.1.

请注意,现有浏览器通常会忽略该scoped属性并允许style几乎任何位置的元素,并将其内容应用于整个HTML文档(甚至是style元素之前的部分).

  • 这个答案现在无效,因为“样式范围”已从 HTML5 中删除。请参阅 /sf/answers/3198442341/。 (5认同)
  • 嘿! W3C验证适用于此但div中的样式不再起作用:( (3认同)