How to correctly load a stylesheet within the body?

16.5k views Asked by At

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?

4

There are 4 answers

1
Ashish Panchal On BEST ANSWER

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);
3
Barney On
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.

0
Afzaal Ahmad Zeeshan On

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.

0
AudioBubble On

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://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet