How to correctly load a stylesheet within the body?

14,024

Solution 1

You can add your css in the head dynamically as well like below:

jsCode:

var head = document.getElementsByTagName("head")[0],
    cssLink = document.createElement("link");

cssLink.href = "path/to/filenam.css";
cssLink.id="dynamic-css";
cssLink.media="screen";
cssLink.type="text/css";

head.appendChild(cssLink);

Solution 2

document.head.appendChild( linkElement );

…where linkElement is your style link. Nobody's forcing you to add stuff to the body, just add it to the head.

Solution 3

It is valid to link to a stylesheet in the body

The stylesheet keyword may be used with link elements. This keyword creates an external resource link that contributes to the styling processing model. This keyword is body-ok.

https://html.spec.whatwg.org/multipage/semantics.html#body-ok https://www.w3.org/TR/html5/links.html#element-statedef-link-stylesheet

Solution 4

Actually in older versions of HTML it was illegal to put a link element in the body element and must be only in the head section of the HTML document. From this link, there is a section that states this

it may only appear in the HEAD section of a document

So, just simply load the stylesheet into the head element, there is no possible reason for you, or for anyone to write illegal documents that do not satisfy the rules of W3.org.

<head>
   <link rel="stylesheet" href="~/css/file.css" />
</head>

However, there is another question that you might be interested in reading, and in which condition you can add link element to the body section. Read the answer here.

Share:
14,024

Related videos on Youtube

thelolcat
Author by

thelolcat

Updated on June 04, 2022

Comments

  • thelolcat
    thelolcat almost 2 years

    I know I can just put the <link> tag in the body and apparently it works, but I know it's not "valid" html and I want to avoid issues with strict browsers like firefox, which ignore every behavior a web designer expects if it's not defined in the official specification.

    So is there some official way to load a stylesheet in the body area of the html?

    • Thomas Bormans
      Thomas Bormans over 9 years
      Why don't you use one stylesheet for everything and load the entire stylesheet from the beginning?
    • Jon P
      Jon P over 9 years
      The specs are there for a reason.... in the dim dark early days of the web when the specs were readily ignored it was anarchy and you had to deal with a whole heap of messing around to deal with browser inconsistencies. Work with the spec not agains it.