Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading