Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does CSS have to be defined within <head> tags?

Tags:

html

css

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?

like image 300
Kiyoshi Avatar asked Aug 02 '11 10:08

Kiyoshi


People also ask

Does CSS have to be in the head?

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.

Can you link CSS outside of head?

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.

What should be contained in the head tags?

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.

Which tag is defined within the head tag?

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.


2 Answers

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.

like image 20
David Thomas Avatar answered Sep 22 '22 17:09

David Thomas


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.

like image 148
kͩeͣmͮpͥ ͩ Avatar answered Sep 24 '22 17:09

kͩeͣmͮpͥ ͩ