首页 > 解决方案 > 选择特定元素

问题描述

伙计们,如果我有很多段落,我不知道如何选择特定的类/id 选择器,而我只想选择一个特定的选择器。例如,如果我想选择第二个段落,我应该怎么做?<p>World</p>我可以以某种方式选择它还是我需要添加另一个类。

例子:

HTML:

<div class="class">
   <p>Hello</p>
   <p>World</p>
</div>

如何选择第二段<p>World</p>

标签: css

解决方案


看看伪类选择器:nth-​​of-type()

在这种情况下,你只需要做.class > div:nth-of-type(2)

.class > p:nth-of-type(2) {
  background-color: red
}
<div class="class">
   <p>Hello</p>
   <p>World</p>
</div>


推荐阅读