What you are asking for is essentially the style of the component inside the section based on the section itself. Unfortunately, this is not possible with CSS, since there is no parent selector in CSS . but inherit value , which allows you a component based on rules defined by its parent - perfect for component based CSS.
In my opinion, the best way you can use an alternative background style is to use :nth-of-type pseudo :nth-of-type class on <section> :
section:nth-of-type(2n) { background: #464646; color: #fff; }
<section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section> <section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section> <section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section> <section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section>
Given that :nth-of-type uses math for the target elements, you can access literally any combination of elements you would like:
// Style every second element, starting with the first element section:nth-of-type(2n - 1) // Style every third element, starting with the second element (2, 5, 8, etc.) section:nth-of-type(3n + 2)
This way, it doesn't matter if you use a component-based approach or not, since you can directly change the style of <section> directly .
Elements that inherit an attribute from internal style sheets (for example, the color of the <a> tag), unfortunately, will still be stylized based on the internal style sheet, and not the rules defined by their parents.
You can get around this using the contextual style:
section:nth-of-type(n) { background: #464646; color: #fff; } section:nth-of-type(n) a { color: #fff; }
<section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section>
Or, alternatively (and preferably) use the inherit value to tell each <a> tag to inherit its color from its parent:
section { background: #464646; color: #fff; } a { color: inherit; }
<section> <h2>Title</h2> <p>Text</p> <a href="#" class="btn">Action</a> </section>
Hope this helps!
source share