鉴于以下标记:
<div>
<p class="eventPerformanceDate">...</p>
<p class="eventPerformance">...</p>
</div>
Run Code Online (Sandbox Code Playgroud)
.eventPerformance如果它是.eventPerformancediv中唯一的段落,我想要定位段落.
我使用以下CSS尝试这样做,但它不起作用:
.eventPerformance:only-of-type {
border-bottom:none;
}
Run Code Online (Sandbox Code Playgroud)
我误解了怎么:only-of-type运作?
Har*_*rry 11
与所有其他CSS *-of-type选择器一样,only-of-type选择器处理元素的类型,而不是附加的附加条件.这里p父类中有两个类型的元素,因此没有效果.
选择器就像.eventPerformance:only-of-type意味着必须选择一个元素,它是父类下唯一的一个元素,如果它也有 class='eventPerformance'.它并不意味着选择唯一的元素class='eventPerformance'和样式.
在代码段中,您可以看到选择器如何影响p第二个div包装器,因为它只有一个p元素.它也会影响p第三个div包装器,因为即使有两个元素,class='eventPerformance'仍然只有一个类型的元素p与该类.在h4第三个内div包装也被选中,因为只有一个它的父类中的元素,它也有类.
该only-of-type选择器将选择的每一个类型的唯一元件,只要有连接到它没有类型选择器(如p:only-of-type,p.eventPerformance:only-of-type等).
在第四个div包装器中,p标签没有样式,即使它是它的唯一类型,因为它与条件的另一半不匹配(即,类选择器不匹配).
p, h4 {
border: 1px solid;
}
.eventPerformance:only-of-type {
border-bottom: none;
}Run Code Online (Sandbox Code Playgroud)
<h3>None of the elements selected - Not only one of its type</h3>
<div>
<p class="eventPerformanceDate">Paragraph 1</p>
<p class="eventPerformance">Paragraph 2</p>
</div>
<h3>Element is selected - Only p and has required class</h3>
<div>
<p class="eventPerformance">Paragraph 1</p>
</div>
<h3>Elements are selected - Both are only element of their type and have class</h3>
<div>
<h4 class="eventPerformance">Heading 1</h4>
<p class="eventPerformance">Paragraph 1</p>
</div>
<h3>Element is not selected - Only p but doesn't have required class</h3>
<div>
<p class="some-other-class">Paragraph 1</p>
</div>Run Code Online (Sandbox Code Playgroud)