问题描述
我有以下标记:
<div class="a"></div>
<div class="b"></div> <!-- :first -->
<div class="b"></div>
<div class="b"></div> <!-- :last -->
<div class="c"></div>
我正在尝试使用类b
定位 first 和 last <div>
.如果我为此使用jQuery选择器,则.b:first
和.b:last
可以解决问题.
I'm trying to target the first and last <div>
with class b
.If I was using jQuery selectors for this, .b:first
and .b:last
would do the trick.
但是对于CSS来说,这很棘手:第一个<div class="b">
位于另一个具有不同类的<div>
之后,并且:first-child和:first-of-type都与第一个<div>
匹配,且类a
.
However with CSS, that's tricky: the first <div class="b">
is located after another <div>
with a different class, and both :first-child and :first-of-type match the first <div>
, with class a
.
是否有一个选择器定位到与该类匹配的第一个项目?
Is there a selector targeting the first of the items matching the class?
推荐答案
不,没有与jQuery的:first
或:last
选择器等效的CSS选择器,因为这些选择器是.
No, there is no equivalent CSS selector to jQuery's :first
or :last
selector, because those selectors are filters, and not true simple selectors by the CSS definition.
选择器3中也没有:first-of-class
或类似的选择器.
In Selectors 3 there is no :first-of-class
or similar selector either.
但是,您可以将覆盖规则与~
组合器一起使用,以将样式应用于特定类的第一个孩子:
However, you can use overriding rules with the ~
combinator to apply styles to the first child of a certain class:
- CSS selector for first element with class
- CSS selector to select first element of a given class
但是目前尚无法使用CSS将样式应用于某个类的最后一个孩子:
But there is currently no way to apply styles to the last child of a certain class using CSS:
这篇关于CSS3中有与jQuery的:first选择器等效的功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!