标题标签的第一个子伪选择器问题

Leo*_*ira 2 html css css-selectors

我今天在设计动态新闻页面时陷入困境,因为我在我的部分开头添加了一个标题标签,而 div 中 ap 标签的第一个孩子停止工作。这就是我想要做的,它一直在工作,直到我添加了标题标签。

.pubs .newsdate {
    border-top:1px solid rgb(255,179,0);
}
.pubs:first-child .newsdate {
    border:none;
}
Run Code Online (Sandbox Code Playgroud)
<section class="content">
    <h2>News</h2> //issue
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
    <div class="pubs">
        <p class="newsdate">stuff</p>
    </div>
</section>
Run Code Online (Sandbox Code Playgroud)

第一个边框被正确删除,直到我添加了标题 (h2) 标签。然后,伪选择器停止工作。可能发生了什么?

Tyl*_*erH 5

.pubs:first-child查找pubs 也是其父元素的第一个子元素的类(在这种情况下,父元素是 class content。一旦h2在第一个pubs类之前添加元素,则pubs不再是第一个子元素,而是第二个.

试试吧.pubs:first-of-type

.pubs:first-of-type .newsdate {
    border: none;
}
Run Code Online (Sandbox Code Playgroud)

:first-of-type伪选择将寻找第一类型为准类或ID或元素的你前面加上它。我的意思是,元素 ( div)、类 ( .pub) 或 ID ( #pub) 是否出现在伪选择器之前并不重要(每个都是有效的)。尽管使用 ID 没有多大意义,因为它们应该是唯一的。

还要注意我说的是 first type,而不是 first instance(两个人已经对我在说什么感到困惑(一个人删除了他们的评论)。例如,如果你有.pubs三个div元素和两个p元素的类,你的:first-of-type伪选择器将应用于第一个.pubs div元素第一个.pubs p元素。

所以first-of-type伪选择器可以应用于多个元素,这取决于你如何使用它。

如果您考虑一下,这是一个比您第一次使用时更好的解决方案,因为该解决方案专门针对类的第一个实例.pubs,而您的示例仅在环境中起作用(当之前没有任何内容时.pubs)。

  • @LeonardoFerreira 查看这个[酷游戏](http://flukeout.github.io/) 来测试您对伪选择器的了解。它很短,很有趣,而且非常有价值! (2认同)