[英]CSS selector to select first and last element under parent, when html structure is not deterministic
[英]CSS - selector for first element anywhere under a parent
如何在不使用特定 div 的情況下獲取下面“標簽 1”的選擇器? 我認為#wrapper label:first-of-type
可以解決問題,但這似乎是選擇每個標簽。
<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
不起作用,因為每個label
都是其直接父級中的第一個類型。 這是這里的關鍵,這些類型的選擇器總是相對於直接父級。
所以,你可以做這樣的事情:
#wrapper div:first-child > label
這將選擇任何label
元素,這些元素是div
的直接子元素, div
是其父元素中的第一個子元素
使用 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 可以很容易地做到這一點,它會是這樣的: (///*[@id="wrapper"]//label)[1]
我還沒有在 css 中找到它的等效性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.