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

CSS descendant selector – anchor element in beginning of descendant list breaks styling

I’m trying to apply styling for only the p and a elements that are a descendant of any element with class "some-class". Per https://developer.mozilla.org/en-US/docs/Web/CSS/Selector_list, the code below should provide the expected behavior. However, the styling is unexpectedly being applied to all the p elements. Interestingly, I am able to get the correct behavior if I reorder the list of descendants, i.e. .some-class p,a. Can someone explain why this might be?

FYI – I’ve run the code in both Firefox and Chrome with the same results.

<html>
<head>
<style>
.some-class a,p {
     color: red;
}
</style>
</head>
<body>

<div>
    <p>should not be red</p>
</div>

<div class="some-class">
    <p>should be red</p>
</div>

</body>
</html>

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

>Solution :

You select all a-elements that are inside elements with a classname of some-class, then you select all p-elements. You must specify that you also want to select all p-elements that are inside elements with a classname of some-class, like this:

.some-class a,
.some-class p {
   color: red;
}

And a more modern way of doing the same:

.some-class :is(a,p) {
   color: red;
}
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