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

问题描述 投票:0回答:1
<!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.

据我了解,“作用域”属性使样式标签可以位于文档头部之外。那么为什么验证者对此不满意呢?

(我使用的是 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 标签之后,它就会这样做。这是什么原因?

html css w3c-validation
1个回答
19
投票

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
元素之前的部分)。

© www.soinside.com 2019 - 2024. All rights reserved.