Reputation: 11625
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?
Upvotes: 5
Views: 17228
Reputation:
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
Upvotes: 6
Reputation: 504
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);
Upvotes: 15
Reputation: 15860
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.
Upvotes: 1
Reputation: 16466
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.
Upvotes: 9