我有一段HTML我无法编辑(不使用JavaScript)。选择嵌套的第一个子元素没有兄弟与css
我想用CSS隐藏段落。该段没有id
。有什么办法只针对它,而不是它的兄弟<p>
与CSS?
HTML:
<div id="foo">
<div></div>
<p> this is the paragraph to hide</p>
<p> this one should not be affected</p>
</div>
我有一段HTML我无法编辑(不使用JavaScript)。选择嵌套的第一个子元素没有兄弟与css
我想用CSS隐藏段落。该段没有id
。有什么办法只针对它,而不是它的兄弟<p>
与CSS?
HTML:
<div id="foo">
<div></div>
<p> this is the paragraph to hide</p>
<p> this one should not be affected</p>
</div>
这取决于你的标记结构。如果<p>
是其父的第一个孩子,您可以使用:first-child
伪类如下:
#foo p:first-child { /* or simply #foo :first-child */
background-color: gold;
}
注:如果只想选择直接<p>
孩子,您应该使用children selector(a > b
)作为:#foo > p:first-child
。
但是,如果有其他兄弟姐妹第一<p>
元素之前,你可以使用CSS3 :first-of-type
伪类在其父的孩子树来选择第一<p>
元素:
#foo p:first-of-type {
background-color: gold;
}
同样,对于直接的孩子,您可以使用#foo > p:first-of-type
。
从MDN:
的
:first-of-type
CSS伪类表示 其类型在其父元素的子列表中的第一个兄弟。
有关更多信息,请参阅my answer。
这是其母公司的第一个孩子,这样你就可以明确选择:
#foo > p:first-child
我刚刚使用'background-color'来突出显示所选元素。显然你应该使用'display:none;'来隐藏元素。 –