Search code examples
htmlcssencapsulation

How to encapsulate CSS, especially for popups and no iframe involved?


Just got a new webpage with css for a fancy box popup from the design team;

And they don't know or don't care to look for existing classes and ids;

I need a working solution without any IFRAME

The problem is that there are already over 20.000 css lines in the main css file, and at some point something will get overwritten and the entire website will do a big BANG!

This new webpage has very common class and id names, and I am talking about almost 100 tags with css properties;

I want to know if there is a method to encapsulate this new css properties and the future ones;

And if there is a way to do this, how can it be done?

With this webpage I got lucky, I pasted the tags with content and just before this, I used the style type"text/css' tag; But i will not always be lucky;

Just because we get webpages with css code written by different people, it does not seam fair to me to create new css classes if some of the properties or names or ids intersect with each other.

I now have about 10 classes for the a tag and im most part, the properties are the same;


Solution

  • Use targeted rules and let the cascade take care of it for you. Put your popup in a wrapper with as detailed of a name as you like.

    <div id="myPopupDivWithCommonIds">
        <!-- rest of popup -->
    </div>
    

    And target your css rules to that div.

    #myPopupDivWithCommonIds .error { color: bright-pink; }
    #myPopupDivWithCommonIds #main { width: 93.21%; }
    

    Etc. etc. This takes care of the css rules and prevents your new stuff from overflowing. You will have to take care to make sure none of the other rules trickle down; the best way for that is to judiciously overwrite any properties that are defined (what Pekka said). You could also go nuclear on it and include a custom 'reboot' or 'bootstrap' stylesheet and again re-target all of its rules to your new popup div (like you said, it's difficult for 20k lines of css; but including another file with the resets rules targeted to your div by appending the #id selector as above helps a little).

    Oh, and that still doesn't address the problem of repeated ids technically being invalid markup and very likely to interfere with any JavaScript you're trying to run on that page.

    If this sounds like a mess, well, it is. Your developers and designers have got it to that point and short of a serious refactoring, you're not going to get back to a clean solution. An iFrame may seem like a hack or impossible for your use case, but it really would clean up a lot of your correctly foreseen problems.