html - nth-of-type 选择器未按预期工作
问题描述
我只想从 中选择第一个和h2
第一个,因此我使用了这个 CSS:p
#section_5
#section_5 div:nth-of-type(1) h2{
color:green;
}
#section_5 div:nth-of-type(1) p{
color:blue;
}
但它会选择#section_5
似乎不满足选择器的所有其他子 div:nth-of-type(1)
/*style the more features title*/
#section_5 div:nth-of-type(1) h2{
color:green;
}
/*style the more features paragraph*/
#section_5 div:nth-of-type(1) p{
color:blue;
}
<div id="section_5">
<div class="row just_space1 title">
<div class="col-12 text-center">
<h2>The Limitation Of Design Is Never Ending With Our Features</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero quod consequuntur
quibusdam, enim expedita sed quia nesciunt incidunt accusamus necessitatibus modi
adipisci officia libero accusantium esse hic, obcaecati, ullam, laboriosam!</p>
</div>
</div>
<div>
<div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
</div>
<!-- /Features column 1 -->
<!--Image to style the section-->
<div class="col-12 col-md-8">
<p>
ssss
</p>
</div>
<div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
</div>
</div>
</div>
<!--/Section 5-->
你能解释一下吗,还是我做错了?
解决方案
您需要考虑>
选择器以避免选择嵌套元素。您的选择器将选择任何级别的所有div
内容,而nth-of-type(1)
不仅仅是.div
#section5
/*style the more features title*/
#section_5 > div:nth-of-type(1) h2 {
color: green;
}
/*style the more features paragraph*/
#section_5 > div:nth-of-type(1) p {
color: blue;
}
<div id="section_5">
<div class="row just_space1 title">
<div class="col-12 text-center">
<h2>The Limitation Of Design Is Never Ending With Our Features</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero quod consequuntur quibusdam, enim expedita sed quia nesciunt incidunt accusamus necessitatibus modi adipisci officia libero accusantium esse hic, obcaecati, ullam, laboriosam!</p>
</div>
</div>
<div>
<div> <!-- this div is also nth-of-type(1) -->
<div> <!-- this div is also nth-of-type(1) -->
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
</div>
<div class="col-12 col-md-8">
<p>
ssss
</p>
</div>
<div>
<div> <!-- this div is also nth-of-type(1) -->
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
<div>
<span></span>
<p>Danything</p>
<h2>anything t</h2>
<p>anything</p>
</div>
</div>
</div>
</div>
<!--/Section 5-->