CSS 伪类 :only-of-type 匹配或表示在同一父容器中没有相同类型同级的元素。
由此选择的元素伪类必须有一个父类。
语法
:only-of-type {
/* ... */
}
- 1
- 2
CSS :only-of-type 示例
这里是 :only 的示例-of-type 伪类,应用于 <div> 父元素下的 <p> 和 <h2> 标记:
<html>
<head>
<style>
.field {
margin: 1px;
padding: 1px;
}
p:only-of-type {
color: darkblue;
background-color: lightpink;
padding: 5px;
}
h2:only-of-type {
text-decoration-line: underline;
color: green;
}
div {
border: 2px solid black;
width: 500px;
}
</style>
</head>
<body>
<div class="field">
<h2>Heading 2 - only type</h2>
<p>Paragraph tag - only type</p>
</div>
<div class="field">
<h2>Heading 2 - only type</h2>
<p>Paragraph tag 1 - we are two</p>
<p>Paragraph tag 2 - we are two</p>
</div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
在此示例中,CSS 规则仅适用于 <div> 中找到的唯一 <p> 和 <h2> 类型元素父容器。第二个 <div> 只有一个 <h2> 类型元素,但有两个 <p> 元素,因此该样式仅应用于 <h2> 元素,而不应用于 <p> 元素。