Search code examples
htmlcsscgi

Is it correct to use the <style> tag outside of the <head> element?


Is it correct to use the <style> tag outside of the <head> element ?

Like this:

<html>
<head>
<style> some style </style>
</head>
<body> some text </body>
<style> some more style </style>
<body> some more text </body>
</html>

I want to do this because: my cgi sources other files with their own style.

The cgi file contains:

#!/bin/bash
echo "content-type: text/html"
echo ""
echo "<html><head><style>"
echo "h1 {color: red;}"
echo "</style>"
echo "<body>"
echo "<h1> some text here </h1>"
echo "</body>"
source ./data.sh
echo "</html>"

And the source file contains:

echo "<style>"
echo "h2 {color: blue;}"
echo "</style>"
echo "<body>"
echo "<h2> and some other text here </h2>"
echo "</body>"

This seems to work fine. But is it correct ?

At w3schools it says: Each HTML document can contain multiple <style> tags.
But is it done this way ?


Solution

  • style is supposed to be included only on the head of the document.

    Besides the validation point, one caveat that might interest you when using style on the body is the flash of unstyled content. The browser would get elements that would be styled after they are displayed, making them shift on size/shape/font and/or flicker. It is generally a sign of bad craftsmanship. Generally you can get away with putting style anywhere you want, but try to avoid it whenever it is possible.

    HTML 5 introduced a scoped attribute that allowed style tags to be included everywhere in the body, but then they removed it again.

    According to the W3 specs, <link> tags are only supposed to go in the <head> section:

    References

    For HTML 4.01: http://www.w3.org/TR/html401/struct/links.html#edef-LINK

    For HTML5: http://www.w3.org/TR/html5/document-metadata.html#the-link-element

    Validation Issues

    If you put a tag within the body of the HTML document, it will not validate using validate.w3.org