Take the 2-minute tour ×

Is there a way to add css from a string in the javascript file to the head of a document with javascript?

Let's say we have a webpage, which has a lightbox script, this script requires a css file to function.

Now adding this css file with <link> will make the css file download even for people that don't have js enabled.

I know that I can dynamically load the css file with the script, but that also means that there will be 2 http requests, and in cases where there is little to no css in the file I find this inefficient.

So I thought to myself, what if you could put the css that you have in the css file, into the script, have the script parse the css and add it into the head, or even better just have the script add the css directly into the <head> of the document.

But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?


I edited roryf's answer to work cross browser (except IE5)


 function addcss(css){
    var s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    if (s.styleSheet) {   // IE
        s.styleSheet.cssText = css;
    } else {                // the world
share|improve this question
Have a look at the following link .. It explains every little details about your question ... and it is named appropriately Totally Pwn CSS with Javascript –  Gaby aka G. Petrioli Oct 13 '10 at 9:07
add comment

4 Answers

up vote 12 down vote accepted

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  # other stuff..

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!


share|improve this answer
That's fine until you want to add a CSS rule after the document has rendered. –  Tim Down Oct 13 '10 at 9:36
Good thing OP doesn't have that requirement then! Your solution covers that, but imho it's totally overkill for non-js/lightbox css degradation as this. –  Jeriko Oct 13 '10 at 9:50
Yes, you're probably right. –  Tim Down Oct 13 '10 at 10:29
One thing to note: document.write doesn't work in real XHTML documents, but that's unlikely to be a problem since hardly anyone really uses XHTML. –  Tim Down Oct 13 '10 at 10:30
it's interesting that it works but having style in the body looks a bit hacky :) p.s. you can put the document.write in the head section of the site and it seems to work fine. –  Timo Huovinen Oct 13 '10 at 12:06
show 12 more comments

You could use the jQuery library to select your head element and append HTML to it, in a manner like:

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

You can find a complete tutorial for this problem here

Using jQuery is very easy and I suggest using it, in the case you're not already are.

share|improve this answer
Again, this method loads a new file, which Yuri wanted to avoid. Also, loading the entire jQuery library for something as simple as this is rather silly. –  TRiG Oct 13 '10 at 9:13
add comment

A simple non-jQuery solution, albeit with a bit of a hack for IE:

var css = ".lightbox { width: 400px; height: 400px; border: 1px solid #333}";

var htmlDiv = document.createElement('div');
htmlDiv.innerHTML = '<p>foo</p><style>' + css + '</style>';

It seems IE does not allow setting innerText, innerHTML or using appendChild on style elements. Here is a bug report which demonstrates this, although I think it identifies the problem incorrectly. The workaround above is from the comments on the bug report and has been tested in IE6 and IE9.

Whether you use this, document.write or a more complex solution will really depend on your situation.

share|improve this answer
Doesn't work in IE. Certainly not 6 or 7, don't have 8 available to test right now. IE doesn't like document.createElement('style'). –  Tim Down Oct 13 '10 at 9:51
@Tim works for me in IE6 and 9, since your solution has the exact same line perhaps you can explain further –  roryf Oct 13 '10 at 10:19
@roryf: Oh, yes, you're right, sorry. Foolishly I made the elementary mistake of believing the line number in IE's error. The error's actually in styleElement.innerHTML = css;. Certainly fails in IE 7, retesting in IE 6 now (waiting for VM to come alive). –  Tim Down Oct 13 '10 at 10:25
@roryf: Same error in IE 6. –  Tim Down Oct 13 '10 at 10:34
@Tim thanks, I suspected that might be a problem, shame on me for not testing properly! –  roryf Oct 13 '10 at 11:12
show 8 more comments

Here's a function that will dynamically create a CSS rule in all major browsers. createCssRule takes a selector (e.g. "p.purpleText"), a rule (e.g. "color: purple;") and optionally a Document (the current document is used by default):

var addRule;

if (typeof document.styleSheets != "undefined" && document.styleSheets) {
    addRule = function(selector, rule) {
        var styleSheets = document.styleSheets, styleSheet;
        if (styleSheets && styleSheets.length) {
            styleSheet = styleSheets[styleSheets.length - 1];
            if (styleSheet.addRule) {
                styleSheet.addRule(selector, rule)
            } else if (typeof styleSheet.cssText == "string") {
                styleSheet.cssText = selector + " {" + rule + "}";
            } else if (styleSheet.insertRule && styleSheet.cssRules) {
                styleSheet.insertRule(selector + " {" + rule + "}", styleSheet.cssRules.length);
} else {
    addRule = function(selector, rule, el, doc) {
        el.appendChild(doc.createTextNode(selector + " {" + rule + "}"));

function createCssRule(selector, rule, doc) {
    doc = doc || document;
    var head = doc.getElementsByTagName("head")[0];
    if (head && addRule) {
        var styleEl = doc.createElement("style");
        styleEl.type = "text/css";
        styleEl.media = "screen";
        addRule(selector, rule, styleEl, doc);
        styleEl = null;

createCssRule("body", "background-color: purple;");
share|improve this answer
Very thorough answer, and I believe it will come in handy, but it will be painstaking to take a simple css stylesheet and convert it to this. –  Timo Huovinen Oct 13 '10 at 12:07
Yes, you're right. I'd use @Jeriko's answer if I were you. –  Tim Down Oct 13 '10 at 12:11
add comment

Your Answer


