【问题标题】:Element style not allowed as child of element body in this context (<style scoped> not validating)在此上下文中,元素样式不允许作为元素主体的子元素(<style scoped> 未验证)
【发布时间】:2015-02-16 19:08:56
【问题描述】:
<!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>

但如果脚本标签在样式标签之后,它会这样做。这是什么原因?

【问题讨论】:

    标签: html css w3c-validation


    【解决方案1】:

    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>
    

    根据 W3C 建议 HTML5scoped 属性根本无效。它出现在 HTML5 草案中,但由于缺乏实现而被从建议中删除,但它仍处于“标准化轨道”,可能会进入 HTML 5.1。

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

    【讨论】:

    • 嘿! W3C 验证适用于此,但 div 中的样式不再适用:(
    • 这个答案现在无效,因为 style scoped 已从 HTML5 中删除。见stackoverflow.com/a/45692033/1219634
    猜你喜欢
    • 2013-12-08
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多