2016-07-14 92 views
1

我试图直接在其.page-container父级中直接定位.row的第一个实例。我无法使:first-of-type选择器正确定位.row的第一个实例。不能使用具有子选择器的第一种类型的选择器

.page-container > .row:first-of-type { 
 
    background: blue; 
 
}
<div class="page-container"> 
 
    <div class="row">Target This Row</div> 
 
    <div class="row">Don't Target</div> 
 
    <div class="row">Don't Target 
 
    <div class="row">Don't Target</div> 
 
    </div> 
 
</div>

请帮我的目标只有.row第一个实例是.page-container的直系后裔。

+1

https://jsfiddle.net/k54x0czj/ – potashin

+1

作为@potashin指出的那样,你的代码似乎工作得很好。除非我们误解了你的问题? – Quiver

回答

3

我碰到这个问题跑了相对较近。

的问题是,:first-of-type具体是指第一-此型OF-的元件和它不能(并且不)适用于类。

为了有适用于类的选择,我们需要或者:first-of-class:first-of-query(可以选择什么 - 包括类) - ,到目前为止,既不存在。

因此你需要的东西是这样的:

.page-container div:first-of-type.row 

这意味着:嵌套.page-container

第一div - 但只有如果 也恰好有类.row

0

我想你想要的是

.page-container > .row:first-child { 
    background: blue; 
} 
0

我通常会忽略类或id并集中在标记名称上,如果它太宽泛,我会通过向父级添加class或id来缩小它的范围。

div > div:first-of-type { 
 
    background: blue; 
 
} 
 
div.page-container > div:first-of-type { 
 
    border: 3px solid red; 
 
} 
 
p:first-of-type { 
 
    color: blue 
 
} 
 
p:last-of-type { 
 
    color: red; 
 
}
<p>Example #1 in blue background</p> 
 
<p>Example #2 in red border</p> 
 
<div class="page-container"> 
 
    <div class="row">Target This Row</div> 
 
    <div class="row">Don't Target</div> 
 
    <div class="row">Don't Target 
 
    <div class="row">Don't Target</div> 
 
    </div> 
 
</div>