我之前问了一个类似的问题,但我找到了一个更好的方法来说出来.所以,给定一个有多个div id的html文档,每个div id里面有几个p标签.. like,like,
<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>
Run Code Online (Sandbox Code Playgroud)
我如何专门针对id'测试'的第二个p标签而不影响第二个id'testingTwo'的第一个p标签?
您可以使用nth-of-type选择器来选择第二个p元素.
通过#testing在选择器中使用,您只需要定位元素内部的#testing元素.所以,你不必担心p其他地方的元素.
#testing p:nth-of-type(2) {
color: green;
font-weight: bold;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
作为替代方案,您还可以使用#testing :nth-child(3)选择元素内的第三个子#testing元素.但是,这不是一种可靠的方法,因为标记可能会更改,但这不起作用.
#testing :nth-child(3) {
color: red;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)