Strictly speaking, do style
tags need to be inside the head
of an HTML document? The 4.01 standard implies that, but it's not explicitly stated:
The STYLE element allows authors to put style sheet rules in the head of the document. HTML permits any number of STYLE elements in the HEAD section of a document.
I say "strictly speaking" because I have an app that puts style elements inside the body, and all the browsers I've tested with seem to use the style elements. I'm just wondering if that's actually legal.
A style tag anywhere but inside the
<head>
will not validate with W3C rules.According to the latest WhatWG and W3C specs, yes,
style
elements must always be in thehead
. For a while, the specs included ascoped
attribute forstyle
elements which, when present, allowed them to be placed within an element in the body to style only that element's descendants... but that feature never made it to any real browser (at least not without needing to be enabled via a developer flag) and was removed from both specs "due to lack of implementer interest". Consequently,style
elements are now only permitted in contexts that allow metadata content, which is only the head.(Okay that's not quite true - you can legally put metadata content, including
style
elements, inside atemplate
element inside thebody
, but it won't actually take effect if you're in a browser that supports templates. This is really just a silly technicality.)The WhatWG spec has this to say:
CTRL-Fing through the single-page spec reveals that the only element whose content model includes metadata content is the
head
element.Meanwhile, the latest W3C draft spec contains exactly identical wording, except that they also list metadata content in the content model of
template
elements. (WhatWG conceptualisestemplate
s differently and lists their content model asnothing
.)The non-normative index of elements in the WhatWG spec confirms that the only permissible parents for a
style
element are ahead
ornoscript
element. (The W3 version of the same index wrongly states that flow content can contain<style>
elements, but this is an error introduced by the W3C at the time of removing thescoped
attribute. I have a pull request open to fix it.)According to this site, HTML5.1 (in draft) and WHATWG allow the
<style>
tag to be put in the body:http://www.html.am/tags/html-style-tag.cfm
It also seems to have been supported by browsers for quite a while. According to this StackOverflow answer, Firefox 3+, IE6+, Safari 2+ and Chrome 12+ support it:
https://stackoverflow.com/a/10989663/297793
The HTML5.2 W3C Recommendation, 14 December 2017 (not the earlier draft referred to above) now says you can include
<style>
.