Can a component be styled based on its closest parent in pure CSS?

yotube
0

Issue

If I use this css, the span's text color is determined by its closest parent (i.e. text is blue):



.red {
color: red;
}

.blue {
color: blue;
}

.green {
color: green;
}

<div class="green">
<div class="red">
<div class="blue">
<div class="my-component">
<span>Hello World</span>
</div>
</div>
</div>
</div>



However, I want this behavior for .my-component specifically. I therefore added .my-component to my selector but suddenly, the span's text color is determined by the definition order (i.e. text is green):



.red .my-component {
color: red;
}

.blue .my-component {
color: blue;
}

.green .my-component {
color: green;
}

<div class="green">
<div class="red">
<div class="blue">
<div class="my-component">
<span>Hello World</span>
</div>
</div>
</div>
</div>



Why is this?

EDIT

Ok, so I messed up a bit here. As noted in the comments, I was mostly surprised that the distance between .red and .my-component did not affect specificity. However, my second question was the one I was really interested in. This question has already received a lot of great answers to the first question, so I'm reverting this question to its original state and will split the second question off into a new one. Thank you all for the great answers!


Solution

Given that the question was (originally) titled: "Can a component be styled based on its closest parent in pure CSS?" and looking at the original examples given you can do it like this:



.red > .my-component {
color: red;
}

.blue > .my-component {
color: blue;
}

.green > .my-component {
color: green;
}

<div class="green">
<div class="red">
<div class="blue">
<div class="my-component">
<span>Hello World</span>
</div>
</div>
</div>
</div>



The > demands a direct parent-child relationship. A "grandparent" will have no effect on the target element's formatting.

However, the above snippet will not work if the target div is placed several levels under the innermost "colored" div.



Answered By - Carsten Massmann
Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top