Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Usually I have a CSS file which has the following rule:

#my-window {
    position: fixed;
    z-index: 102;
    display:none;
    top:50%;
    left:50%;
}

How can I avoid creating such a static CSS file by adding the CSS-information during runtime actions to the body or something similar. (only using jQuery)

I want to define it once but with jQuery use it a lot of time later, that's why I do not want to add it each time to the specific DOM elements.

I know the simple features css("attr1", "value"); but how can I create a complete reusable CSS rule?

share|improve this question
add comment (requires an account with 50 reputation)

16 Answers

You can create style element and insert it into DOM

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");

tested on Opera10 FF3.5 iE8 iE6

share|improve this answer
3  
This works great on ie6, ff3.6, Opera, and Chrome: gist.github.com/714352. This page can help you see for yourself: ipinfo.info/netrenderer/index.php – Daniel Ribeiro Nov 24 '10 at 20:33
The gist is self sufficient. You can create it locally, and it will work just fine. Direct link to the download link: gist.github.com/gists/714352/download – Daniel Ribeiro Nov 25 '10 at 19:43
No problem. Sometimes it can be jQuery minor version bug, or just an incorrect setup. The deal with js apps is this: if they don't work, they just don't work at all. No forgiveness. – Daniel Ribeiro Nov 27 '10 at 0:37
1  
Throws an 'Unexpected call to method or property access' error for me in IE8. I had to follow this article to get it working. – Brandon Boone May 7 '12 at 13:24
There can be only 31 styles in page in IE9- blogs.msdn.com/b/ieinternals/archive/2011/05/14/… – IvanH Nov 16 '12 at 13:22
show 1 more commentadd comment (requires an account with 50 reputation)

you can apply css an an object. So you can define your object in your javascript like this:

var my_css_class = { backgroundColor : 'blue', color : '#fff' };

And then simply apply it to all the elements you want

$("#myelement").css(my_css_class);

So it is reusable. What purpose would you do this for though?

share|improve this answer
2  
I would say this is a CSS rule and not a CSS class. – hippietrail Nov 22 '12 at 8:42
1  
This answer is misleading. The asker wanted to create a CSS rule at runtime, not set the style of a particular element to a constant (reusable) CSS declaration. – Dan Dascalescu Dec 18 '12 at 12:28
1  
It's not quite what they asked for, but it is the right solution :) Filling the dom with extra <style> elements has some nasty code smell – Kevin Mar 24 at 21:36
add comment (requires an account with 50 reputation)

If you don't want to hardcode the CSS into a CSS block/file, you can use jQuery to dynamically add CSS to HTML Elements, ID's, and Classes.

$(document).ready(function() {
  //Build your CSS.
  var body_tag_css = {
    "background-color": "#ddd",
    "font-weight": "",
    "color": "#000"
  }
  //Apply your CSS to the body tag.  You can enter any tag here, as
  //well as ID's and Classes.
  $("body").css(body_tag_css);
});
share|improve this answer
This answer is not quite what the asker asked for. The asker wanted to create a CSS rule at runtime, not set the style of a particular element to a constant CSS declaration. – Dan Dascalescu Dec 18 '12 at 12:29
I understand, but this is an alternative solution, so I provided it. – Mike Trpcic Dec 18 '12 at 20:00
add comment (requires an account with 50 reputation)

Simply

    $("<style>")
    .prop("type", "text/css")
    .html("\
    #my-window {\
        position: fixed;\
        z-index: 102;\
        display:none;\
        top:50%;\
        left:50%;\
    }")
    .appendTo("head");

Noticed the back slashes? They are used to join strings that are on new lines. Leaving them out generates an error.

share|improve this answer
add comment (requires an account with 50 reputation)

What if you dynamically wrote a < script > section on your page (with your dynamic rules) and then used jQuerys .addClass( class ) to add those dynamically created rules?

I have not tried this, just offering a theory that might work.

share|improve this answer
seams teh best way right now. i've found something jQuery.cssRule but is some kind of plugin :-/ – stephan Jul 31 '09 at 13:39
1  
$("head").append($("<style type='text/css'> ... is one way – stephan Jul 31 '09 at 13:46
add comment (requires an account with 50 reputation)

Bit of a lazy answer this, but the following article may help: http://www.javascriptkit.com/dhtmltutors/externalcss3.shtml

Also, try typing "modify css rules" into google

Not sure whatwould happen if you tried to wrap a document.styleSheets[0] with jQuery() though you could give it a try

share|improve this answer
add comment (requires an account with 50 reputation)

You can use a the cssRule plug-in. The code was simple then:

$.cssRule("#my-window {
    position: fixed;
    z-index: 102;
    display:none;
    top:50%;
    left:50%;
}");

One of the comments so far asked why one would want to do such a thing. For example, creating styles for a list where each item needs a distinct background colour (eg. GCal's list of calendars) where the number of columns is not known until run time.

share|improve this answer
Taras Bulba works just fine. – Daniel Ribeiro Nov 24 '10 at 20:35
@Daniel, yes it does; statement removed. – Robert Gowland Nov 26 '10 at 21:20
seems doesn't support rule like this: div:before{content:'name: ';} – liuyanghejerry Dec 9 '11 at 14:44
add comment (requires an account with 50 reputation)

if you don' t want to assign a display:none to a css class, the right approach in to append to style, jQuery.Rule do the job.

I some cases you want to apply stiles before the append event of ajax content and fade content after append and this is it!

share|improve this answer
add comment (requires an account with 50 reputation)

Adding custom rules is useful if you create a jQuery widget that requires custom CSS (such as extending the existing jQueryUI CSS framework for your particular widget). This solution builds on Taras's answer (the first one above).

Assuming your HTML markup has a button with an id of "addrule" and a div with an id of "target" containing some text:

jQuery code:

$( "#addrule" ).click(function () { addcssrule($("#target")); });

function addcssrule(target) 
{ 
var cssrules =  $("<style type='text/css'> </style>").appendTo("head");

cssrules.append(".redbold{ color:#f00; font-weight:bold;}"); 
cssrules.append(".newfont {font-family: arial;}"); 
target.addClass("redbold newfont");     
}       

The advantage of this approach is that you can reuse variable cssrules in your code to add or subtract rules at will. If cssrules is embedded in a persistent object such as a jQuery widget you have a persistent local variable to work with.

share|improve this answer
What a nice idea! I used it in conjunction with the snippet on this page ssdtutorials.com/tutorials/title/jquery-flashing-text.html to allow for toggling a colour (the original would toggle a class only). Thanks! – BGM Mar 27 at 15:11
add comment (requires an account with 50 reputation)

By using .addClass() in jquery we can dynamically add style to elements on page. eg. we have style

.myStyle
{
  width:500px;
  height:300px;
  background-color:red;
 }

Now in ready state of jquery we can add css like .addClass(myStyle)

Check example here : http://www.codegateway.com/2012/03/add-css-style-dynamically-in-jquery.html

share|improve this answer
add comment (requires an account with 50 reputation)

Maybe you can put the style information in a separate class in your css file, e.g.:

.specificstyle {
    position: fixed;
    z-index: 102;
    display:none;
    top:50%;
    left:50%;
}

and then use jQuery at the point of your choosing to add this classname to the element?

share|improve this answer
1  
i want no extern css file! – stephan Jul 31 '09 at 13:36
1  
and you don't want to put the information in the head section of your page either (between style tags)? – JorenB Jul 31 '09 at 13:45
add comment (requires an account with 50 reputation)

I have been messing with some of this recently and i have used two different approaches when programming an iPhone / iPod site.

The first way I came across when looking for orientation changes so you can see whether the phone is portrait or landscape, this is a very static way but simple and clever:

In CSS :

#content_right,
#content_normal{
 display:none;
}

In JS File:

function updateOrientation(){
  var contentType = "show_";
  switch(window.orientation){
   case 0:
   contentType += "normal";
   break;

   case -90:
   contentType += "right";
   break; document.getElementById("page_wrapper").setAttribute("class",contentType);
}

In PHP/HTML (Import your JS file first then in body tag):

<body onorientationchange="updateOrientation();">

This basically chooses a different pre set CSS block to run depending on the result given back from the JS file.

Also the more dynamic way which I preferred was a very simple addition to a script tag or your JS file:

document.getelementbyid(id).style.backgroundColor = '#ffffff';

This works for most browsers but for IE it's best to take away it's ammunition with something tighter:

var yourID = document.getelementbyid(id); 
 if(yourID.currentstyle) { 
  yourID.style.backgroundColor = "#ffffff";      // for ie :@ 
 } else { 
  yourID.style.setProperty("background-color", "#ffffff");        // everything else :)
 }

Or you can use getElementByClass() and change a range of items.

Hope this helps!

Ash.

share|improve this answer
add comment (requires an account with 50 reputation)

Here is a jquery plugin that allows you to inject CSS:

https://github.com/kajic/jquery-injectCSS

Example:

$.injectCSS({
    "#my-window": {
        "position": "fixed",
        "z-index": 102,
        "display": "none",
        "top": "50%",
        "left": "50%"
    }
});
share|improve this answer
add comment (requires an account with 50 reputation)

Here you have a function to get the full definition of a CSS class:

getCSSStyle = function (className) {
   for (var i = 0; i < document.styleSheets.length; i++) {
       var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
       for (var x = 0; x < classes.length; x++) {
           if (classes[x].selectorText  && - 1 != classes[x].selectorText.indexOf(className)) {
               return classes[x].cssText || classes[x].style.cssText;
           }
       }
   }
   return '';
};
share|improve this answer
add comment (requires an account with 50 reputation)

You can use insertRule if you don't need to support IE < 9, according to dottoro. There's a bit of cross browser code over there as well.

document.styleSheets[0].insertRule('#my-window {\
    position: fixed;\
    z-index: 102;\
    display:none;\
    top:50%;\
    left:50%;\
}', 0)
share|improve this answer
add comment (requires an account with 50 reputation)

You could just make a css class called something like .fixed-object that has all your css in it...

.fixed-object{
    position: fixed;
    z-index: 102;
    display:none;
    top:50%;
    left:50%;
}

Then in jquery anytime you want something to have that style just add that class to it...

$(#my-window).addClass('fixed-object');

That seems like the easiest way to do it, unless I'm misunderstanding what you need done.

share|improve this answer
3  
i want no extern css file! – stephan Jul 31 '09 at 13:38
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.