Apply unknown (at time of programming) stylesheet to only one div

36 Views Asked by At

I want to be able to have a system where I load a static HTML page dynamically, unknown to the developer at the time of programming, and have that stylesheet apply to just one DIV.

There are some questions that address how to do that in some specified setup like applying Bootstrap CSS to one DIV (Applying a Stylesheet Within One Div Only, Apply CSS Stylesheet to only one Div), but not to an unknown stylesheet.

I would ideally like to be able to add CSS like the following pseudocode:

div.foreign-style-sheet
    {
    /* Contents of original stylesheet included at runtime. */
    }

but I do not find suggestions of an approach like this in the specific stylesheet mentioned in the cases above.

Given that scoped stylesheets are apparently deprecated, is there a clean way to do this? Or is there a clean way from Python to change all selectors from foo to div.foreign-style-sheet foo? The latter is something I haven't explored in depth how to do, but is there a clean and non-deprecated frontend way to have a stylesheet only apply to a scope, or should I work on a server-side (Python) adaptation that can input CSS and prepend a given string to every selector?

1

There are 1 best solutions below

0
Brett Donald On

So let’s say that the original stylesheet contains the following:

h1 {color: blue;}
p {color: red;}

And you want to be able to import these rules into another document using Ajax and nest them inside a style rule which applies to single div, something like this:

div.foreign-style-sheet {
  h1 {color: blue;}
  p {color: red;}
}

CSS has recently added support for nesting like this, and current versions of all major browsers now support it too. So if you are happy to ignore older browsers, you could probably make the above work.

Otherwise you could do some string processing with regular expressions to find all the selectors in the original stylesheet and prepend div.foreign-style-sheet to all of them.

div.foreign-style-sheet h1 {color: blue;}
div.foreign-style-sheet p {color: red;}