views:

413

answers:

5

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:

style1.css:

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

style2.css:

.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.

+1  A: 

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

Andrew Hare
+16  A: 

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;
}
altCognito
+1 This is a good solution.
Andrew Hare
This could possibly work - the only problem with it is that the user must know about the div ids beforehand, and then edit the style sheet accordingly. I'll also explore fmsf's iframe suggestion. Thank you!
Mike Cialowicz
Facebook handles this for apps by prefixing the css styles you provide and rewriting the HTML/FBML to use the new class/id names.
garrow
A: 

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.

Absolut40
+3  A: 

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.

fmsf
The iframe option sounds interesting. I'll explore this, thanks!
Mike Cialowicz
+2  A: 

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.

anonymous coward
It appears I was a few seconds behind altCognito, who may have given a fuller answer.
anonymous coward