In the past I've used some software which does this, but I can't recall the name. I thought CSSTidy did it but I can't seem to recall how (if that was it).
Basically the way it worked is you could pass a CSS file like:
#foobar{
.red {
color: #FF0000;
}
.blue {
color: #00FF00;
}
}
And then it would return a CSS file like:
#foobar .red {
color: #FF0000;
}
#foobar .blue {
color: #00FF00;
}
That way I could dynamically encapsulate some CSS includes and ensure their CSS does not "break out" to some extent. ShadowDOM doesn't work for this because I want to cascade into this element. It's not intended to prevent malicious code, just simplify development.
I'm fairly certain it was server-side software and not a javascript library, though either would work.
Sass, Less, and other CSS preprocessors is what you're looking for!
Here's a good article that compares some of the more popular options.