简体   繁体   中英

CSS - selector for first element anywhere under a parent

How can I get the selector for "Label 1" below without having to use specific divs? I thought #wrapper label:first-of-type would do the trick but that appears to be selecting every label.

<div id="wrapper">
    <div class="row">
        <div class="content-1">
            <label>Label 1</label>
        </div>
        <div class="content-2">
            <label>Label 2</label>
        </div>
        <div class="content-3">
            <label>Label 3</label>
        </div>
        <div class="content-4">
            <label>Label 4</label>
        </div>
    </div>
</div>

#wrapper label:first-of-type won't work as every label is the first of it's type within it's immediate parent. That's the key here, these sorts of selectors are always relative to the immediate parent.

So, you could do something like this:

#wrapper div:first-child > label

which would select any label elements which are an immediate child of a div which is the first child within it's parent

use nth-child

 #wrapper .content-1:nth-child(1) label{ background: red; }
 <div id="wrapper"> <div class="row"> <div class="content-1"> <label>Label 1</label> </div> <div class="content-2"> <label>Label 2</label> </div> <div class="content-3"> <label>Label 3</label> </div> <div class="content-4"> <label>Label 4</label> </div> </div> </div>

Xpath can do this easily, it would be something like this: (//*[@id="wrapper"]//label)[1]

I have not found its equivalence in css yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM