CSS3 selector :first-of-type with class name?(CSS3选择器:类名的第一个类型?)
问题描述
是否可以使用 CSS3 选择器 :first-of-type
来选择具有给定类名的第一个元素?我的测试没有成功,所以我认为不是?
Is it possible to use the CSS3 selector :first-of-type
to select the first element with a given class name? I haven't been successful with my test so I'm thinking it's not?
代码(http://jsfiddle.net/YWY4L/):
The Code (http://jsfiddle.net/YWY4L/):
p:first-of-type {color:blue}
p.myclass1:first-of-type {color:red}
.myclass2:first-of-type {color:green}
<div>
<div>This text should appear as normal</div>
<p>This text should be blue.</p>
<p class="myclass1">This text should appear red.</p>
<p class="myclass2">This text should appear green.</p>
</div>
推荐答案
不,只使用一个选择器是不可能的.:first-of-type
伪类选择其 type 的第一个元素(div
、p
、等等).将类选择器(或类型选择器)与该伪类一起使用意味着选择一个元素,如果它具有给定的类(或属于给定的类型)并且是其类型中的第一个兄弟姐妹.
No, it's not possible using just one selector. The :first-of-type
pseudo-class selects the first element of its type (div
, p
, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.
不幸的是,CSS 没有提供只选择第一次出现的类的 :first-of-class
选择器.作为一种解决方法,您可以使用以下方法:
Unfortunately, CSS doesn't provide a :first-of-class
selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:
.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }
这里 和 这里.
这篇关于CSS3选择器:类名的第一个类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CSS3选择器:类名的第一个类型?


- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01