Tutorial :Using different CSS sheets with the same rule names for different HTML document elements


I need a way to load multiple style sheets with the same rule names, and then apply them to different elements on a page. Is this possible?

Here's an example of something I'd like to do. Take the two style sheets below:


.size{      color: #FF6600;      font-size: 18px;  }  


.size{      color: #FF0000;      font-size: 14px;  }  

I would like to be able to import both of them into a page (perhaps with an id of some sort), and then set the text inside one particular div to use the rules from style1.css and another div should use the rules from style2.css.

I need to do things this way because it will allow users of my application to upload custom style sheets for different widgets on a page. This scheme should work, provided that the sheets use the same rule naming scheme.


The answer is no you can't do it this way. The rule loaded last will take precedence.

You should differentiate the different widgets with different classes or IDs, and then you won't have the same rules.

#widgetB .size{          color: #FF0000;          font-size: 14px;  }    #widgetA .size{          color: purple;          font-size: 10px;  }  


Maybe you can put each widget within an iframe. In that iframe you would call the custom stylesheet for that widget. That way you would win more modularity as well as allowing you to do what you want directly, without worrying about cheats to go around the problem.


To directly answer your question, "No". The CSS code itself would have to have some kind of context.

As for "it will allow users of my application to upload custom style sheets for different widgets on a page" - the way I read that, I suggest something like wrapping each widget in a unique ID or similar.

Then, users could upload stylesheets with a bit of context, but still the same basic names, as:

#widget-one .size { ... }    #widget-two .size { ... }  

But some kind of context/prefix is necessary.


If you do this the rule declared in the stylesheet that is loaded last will apply to all elements that it matches.


Maybe you could use something like jQuery to remove the default page CSS and replace it with the users stylesheet, basically swapping the stylesheet on the client-side.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »