CSS-Hack - Adding CSS in The Body of a Website

Add stylesheet to Head using javascript in body

Update: According to specs, the link element is not allowed in the body. However, most browsers will still render it just fine. So, to answer the questions in the comments - one really has to add link to the head of the page and not the body.

function addCss(fileName) {

var head = document.head;
var link = document.createElement("link");

link.type = "text/css";
link.rel = "stylesheet";
link.href = fileName;

head.appendChild(link);
}

addCss('{my-url}');

Or a little bit easier with jquery

function addCss(fileName) {
var link = $("<link />",{
rel: "stylesheet",
type: "text/css",
href: fileName
})
$('head').append(link);
}

addCss("{my-url}");

Original answer:

You don't need necessarily add it to the head, just add it to the end of body tag.

$('body').append('<link rel="stylesheet" type="text/css" href="{url}">')

as Juan Mendes mentioned, you can insert stylesheet to the head instead

$('head').append('<link rel="stylesheet" type="text/css" href="{url}">')

And the same without jQuery (see code above)

Why don't we import css in a div?

That document you link to is a 10-year-old draft, and far from the latest. Now, if you look at the latest revision of the Style Attributes spec, which is a 2010 Candidate Recommendation that covers basically the same inline style declarations that we use every day, you won't find any @import rules mentioned anywhere anymore.

This means they took it out, presumably because it didn't make sense in retrospect, or it was difficult to implement, or some other reason entirely.

How bad is it to put a CSS include in the middle of the body?

<link> is only permitted in the <head> section of a document: Document relationships: the LINK element



Related Topics



Leave a reply



Submit