Is there anyway to select only the first descendant using CSS. For example, is there anyway to start at the .container element and style the <li class="example"> with a blue border, but not the <p class="example"> within it?
I know there are a ton of alternative ways to to this in CSS. But is there a way to do it with the exact code below? Meaning use only the selector classes .container and .example, leave the class .container exactly where it is within the HTML below, and use the exact HTML markup below.
<style>
.container .example{
border: 1px solid blue;
}
</style>
<div>
<div class="container">
<ul>
<li class="example"><p class="example"></p></li>
<li class="example"><p class="example"></p></li>
</ul>
</div>
</div>
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
The :first-child selector allows you to target the first element immediately inside another element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
:first-child means "select this element if it is the first child of its parent". :last-child means "select this element if it is the last child of its parent". Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.
Do you mean the "direct child selector"?
.container > ul > li
..here it is your blue border:
.container > ul > li {
border: solid 1px #00f;
}
..to only use classes, you can accomplish that with something like:
.container > * > .example{
border: solid 1px #00f;
}
css2 way (and still the more robust, I think) was to add border to .example
and remove from .example .example
:
.example{
border: solid 1px #00f;
}
.example .example{
border: none;
}
In CSS3, you can do this:
:not(.example) > .example{
border: solid 1px #00f;
}
just beware that this will not prevent .example > div > .example
from getting the blue border too..
but it guarantees no .example
that is direct child of another .example
will get that style.
what about .container :not(.example) > .example
?
I don't thing you can do better with "clean" css (ie. single rule; without resetting etc.).
The meaning of not()
selector is "match any item that doesn't match the selector", not "forbid this selector to match somewhere here in the rule"..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With