CSS3中有与jQuery的:first选择器等效的功能吗? [英] Is there an equivalent to jQuery's :first selector in CSS3?

查看:72
本文介绍了CSS3中有与jQuery的:first选择器等效的功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下标记:

<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:

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆