2015-09-21 62 views
2

我之前問過類似的問題,但我找到了一個更好的方式來說出它。因此,考慮到有多個DIV ID的HTML文檔,裏面it..like數p標籤每個DIV ID,css針對特定的p標籤

<div id="testing"> 
    <h2>Hello</h2> 
    <p>this is number one</p> 
    <p> this is number two </p> 
</div> 
<div id="testingTwo"> 
    <h2>hello again! </h2> 
    <p> i just want this one </p> 

我怎麼會專門針對沒有影響ID「測試」的第二個p標籤第二個id'testingTwo'的第一個p標籤?

回答

6

您可以使用nth-of-type選擇器來選擇第二個p元素。

通過在選擇器中使用#testing,您只針對位於#testing元素內的元素。所以,你不必擔心其他地方的元素。

#testing p:nth-of-type(2) { 
 
    color: green; 
 
    font-weight: bold; 
 
}
<div id="testing"> 
 
    <h2>Hello</h2> 
 
    <p>this is number one</p> 
 
    <p>this is number two</p> 
 
</div> 
 

 
<div id="testingTwo"> 
 
    <h2>hello again! </h2> 
 
    <p>i just want this one</p>

作爲替代方案,你也可以使用#testing :nth-child(3)選擇#testing元素中的第三子元素。然而,這不是一個可靠的方法,因爲標記可能會改變,這是行不通的。

#testing :nth-child(3) { 
 
    color: red; 
 
}
<div id="testing"> 
 
    <h2>Hello</h2> 
 
    <p>this is number one</p> 
 
    <p>this is number two</p> 
 
</div> 
 

 
<div id="testingTwo"> 
 
    <h2>hello again! </h2> 
 
    <p>i just want this one</p>

+0

你先生,是一個天才。非常感謝你 – user201535

1

對於也許最簡單的方法,你可以給你想要一個新的ID或類分開設置p標籤。

<div id="testing"> 
    <h2>Hello</h2> 
    <p>this is number one</p> 
    <p id="mytarget"> this is number two </p> 
    </div> 

然後指定該ID。

+0

這就是我想要做的,但我的任務說我不能改變html文件:\ – user201535

1

嘗試

#testing :nth-child(3) { 
    //code 
} 

使用 '#' 如果定位一個ID,和 ''如果一個類。

+0

這不行,使用'p:nth-​​child(3)',否則首先'p'將會選中 – Tushar

+0

現在這樣也行不通,你需要'#testing'和':nnth ...'之間的空格。請參閱http://jsfiddle.net/tusharj/55prtq2g/ – Tushar

+0

不,你通過增加空格來修復它,嘗試刪除'p',它仍然可以工作。此外,它看起來像這個選擇器選擇第三個'p'元素,但這不是真的,它只是選擇第三個孩子。這是_confusing_。檢查http://jsfiddle.net/tusharj/55prtq2g/1/ – Tushar

0

您可以使用nth-of-type(n) css屬性。這裏n是int值,從1 ... n開始。

解決你的問題:

#testing p:nth-of-type(1) { 
    font-size:18px; 
} 

Codepen演示:Demo

參考MDN Documentation瞭解更多信息

0

您可以通過調用DIV ID和第n個子內針對特定P標籤您要更改的p標籤,例如

 #testing :nth-child(3) { 
     color: red; 
    } 

會在測試中調用第三個p-tag。