Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

Select "first in hierarchy"

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.

update: start with .container

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"..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...