为什么:first-child选择器不适用于div? [英] Why :first-child selector not working on div?
问题描述
我正在使用:first-child
和:last-child
伪选择器选择特定的div,但:first-child
不起作用在我已签入的任何浏览器中.
I am selecting specific divs with the :first-child
and :last-child
pseudo selectors but :first-child
is not working in any browser I have checked it in.
我已经检查了caniuse.com和css-tricks.com,共识是:first-child
得到了广泛的支持,所以我认为也许是一些我不知道的错误的.我在本地节点服务器上运行该应用程序.我已经验证了我的css和我的html.有没有人知道任何可能阻止:first-child
工作的错误?
I've checked caniuse.com and css-tricks.com and the consensus is that :first-child
is pretty widely supported so I'm thinking maybe there is some bug I am not aware of. I am running the app on a local node server. I have validated both my css and my html. Is anyone aware of any bugs that might prevent :first-child
from working?
HTML
<div class="col-md-6 blurbs">
<label>NEWS</label>
<div>
<p>Lorem ipsum dolor spernatur aut odit aut fugit conse oluptate</p>
</div>
<div class="clearfix">
<a class="pull-left">RSS</a>
<a class="pull-right">MORE NEWS</a>
</div>
</div>
CSS
(不起作用)
.news .blurbs div:first-child{
outline: 1px solid red;
height: 260px;
overflow: auto;
margin-bottom: 10px;
}
(工作中)
.news .blurbs div:last-child{
outline: 1px solid red;
width: 95%;
}
推荐答案
:first-child
和:last-child
伪类选择的元素是父级的第一个/最后一个子级,由任何其他链式选择器过滤,因此 div:first-child
实际上不匹配任何内容,因为 .blurbs
中的第一个子级不是 div
.
The :first-child
and :last-child
pseudo-classes select the element that is the first/last child of the parent, filtered by any other chained selector, so div:first-child
does not actually match anything as the first child within .blurbs
is not a div
.
要获得想要的效果,您需要使用的是:first-of-type
伪类,如下所示:
What you need to use to get the effect you are after is the :first-of-type
pseudo-class like this:
.news .blurbs div:first-of-type{
outline: 1px solid red;
height: 260px;
overflow: auto;
margin-bottom: 10px;
}
这篇关于为什么:first-child选择器不适用于div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!