I am just trying to learn better HTML and I came up with this question: If I can move all my embeded JS and CSS to the body tag, what is the purpose of the head tag?
I know in the head I can set and all sorts of meta tags. Ok. But related to scripts and css, does it make any difference placing the code inside
script tags in
body is entirely normal.
Technically, it's invalid to put
style elements1 or
link elements in
body. In practical terms, it's functional and I've never heard of issues related to it, but it's invalid HTML. If you look for them in the DOM later, you may find that the browser has relocated them into
head (possibly a
head it generated itself). (My experience with cheating on
style, which I had to do on a project once for pragmatic reasons, was that it wasn't relocated; can't speak for
Similarly, it's technically invalid for a document not to have any
head content if it's not an iframe src document. From the spec:
... Content Model:
If the document is an
Otherwise: One or more elements of metadata content, of which exactly one is a
titleelement and no more than one is a
E.g., you must have a
head element in your document, and it must have a
title. Note that this doesn't mean you actually have to type
</head> as both tags are sometimes optional (as is the opening
<body> tag). For instance, this is a perfectly valid HTML5 document:
<!doctype html> <html> <title>My Document</title> <div>Hi there</div>
I do not recommend it, but it's valid.
...what is the purpose of the head tag?
From the spec:
headelement represents a collection of metadata for the
It not only includes CSS and script resources, but things such as the
title and frequently a
<meta charset="..."> declaration in case the document is being used without a mechanism that specifies the encoding.
So I'd recommend putting CSS in the
head, being explicit about
head, and including the required
title and the recommended
1 There's been talk of scoped
style elements, which would be valid if they're ever formalized. The idea's been kicking around since at least 2011, but even as of today, neither the W3C spec linked above nor WHAT-WG spec allows