I am currently creating a library for some CSS styles (there are some that are defined by jQuery too, so feel free to use JavaScript/jQuery for the solution - I don't think it's possible with normal CSS either way).
I have some parts that are supposed to only be applied if a parent element with a specific class (in the example .style-container) exists.
Of course this is possible by adding the class in front of every CSS selector.
That takes a lot of data more that needs to be transferred though, so I thought maybe there is a possibility of applying a CSS-file and it's content just to a specific element and it's children instead of the whole document.
Imagine this CSS (far simplified):
h1 {
color: #f00;
border-bottom: 1px solid #000;
}
This HTML document (part inside the body):
<div class="style-container">
<h1>This should be styled</h1>
</div>
<div>
<h1>This should be standard style</h1>
</div>
And now maybe have some JavaScript/jQuery to load the file for just all the elements with the class and it's children.
Note:
There might appear new Elements through JavaScript/jQuery that haven't been there before and I don't really want to load the whole style again then, because that may take a lot resources to load then, in case the content changes very fast.
And waiting isn't an option either, because then the element wouldn't be styled for the time that's being waited.
EDIT: To point out again: I am searching for a better option that the standard CSS children selector, that would work like this:
.style-container h1 {
color: #f00;
border-bottom: 1px solid #000;
}
I want this, because it uses a lot more data to be transferred from server to client. To understand this: I have a part of my code in minimalized form with the selector and without. The one with the selector needs 3698 characters, the version without the selector needs 2538 characters. That is a difference of 1160 characters. Or, in kB we have a difference of 3.61kB - 2.47kB = 1.14kB. That seems very little, but it is only a very small part of the code it's going to be. I am expecting the code to be ten times as big. That makes a difference of 11,4kB. In my opinion that is quite a big amount for mobile devices...
From where I see it you're looking for "scoped CSS", which is defined on MDN, but unfortunately for you is only available in Firefox
That said, the basic CSS solution is anyway the more performant. If you need to add a script, this script will also have some weight (even if not that big) and take CPU time which on mobile may also be of importance. You would be re-inventing the wheel not even making it a perfect circle...