I would like to define a snippet of CSS in my page like this:
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}
</style>
I keep reading that it should be defined within the <head>
element, but it seems to work fine when inline. Can someone confirm if this is okay?
Internal CSS: Requires the <style> element placed inside the head section of an HTML file. External CSS: Requires the <link> element placed inside the head section of an HTML file.
Yes, it can be used outside the <head> element, but it depends on usage. To import a CSS file as quoted, it is recommended that you leave it at the top of the document, within the <head> element for various considerations.
The <head> element is a container for metadata (data about data) and is placed between the <html> tag and the <body> tag. Metadata is data about the HTML document. Metadata is not displayed. Metadata typically define the document title, character set, styles, scripts, and other meta information.
The <head> tag in HTML is used to define the head portion of the document which contains information related to the document. The <head> tag contains other head elements such as <title>, <meta>, <link>, <style> <link> etc.
For HTML 4 the spec says:
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.
Reference: http://www.w3.org/TR/html4/present/styles.html#h-14.2.3.
Their specification of "head
of the document", rather than simply 'document' strongly suggests that elsewhere is inappropriate.
For HTML 5, however, this is relaxed and the style
element can be placed within the document itself:
The style element allows authors to embed style information in their documents. The style element is one of several inputs to the styling processing model. The element does not represent content for the user.
Reference: http://www.w3.org/TR/html5/semantics.html#the-style-element.
Most browsers put it anywhere in the page, but just be aware that it only takes effect from that point onwards. Also, it's not valid HTML if you don't put it in the head element.
Also, it's considered best practise to put it in the head element as it improves page render times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With