Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first Descendant with CSS

Tags:

html

css

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>
like image 636
user782860 Avatar asked Oct 16 '12 20:10

user782860


People also ask

How do you target the first child in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.

How do you select the first element in CSS?

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.

How do I select the first and last child in CSS?

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


1 Answers

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

like image 152
redShadow Avatar answered Oct 13 '22 00:10

redShadow