2014-03-02 46 views
0

我有一段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> 

回答

4

這取決於你的標記結構。如果<p>是其父的第一個孩子,您可以使用:first-child僞類如下:

#foo p:first-child { /* or simply #foo :first-child */ 
    background-color: gold; 
} 

WORKING DEMO

注:如果只想選擇直接<p>孩子,您應該使用children selectora > b)作爲:#foo > p:first-child


但是,如果有其他兄弟姐妹第一<p>元素之前,你可以使用CSS3 :first-of-type僞類在其父的孩子樹來選擇第一<p>元素:

#foo p:first-of-type { 
    background-color: gold; 
} 

WORKING DEMO

同樣,對於直接的孩子,您可以使用#foo > p:first-of-type

MDN

:first-of-type CSS僞類表示 其類型在其父元素的子列表中的第一個兄弟。

有關更多信息,請參閱my answer

+0

我剛剛使用'background-color'來突出顯示所選元素。顯然你應該使用'display:none;'來隱藏元素。 –

2

這是其母公司的第一個孩子,這樣你就可以明確選擇:

#foo > p:first-child