CSS3选择器:first-of-type类名? [英] CSS3 selector :first-of-type with class name?

查看:604
本文介绍了CSS3选择器:first-of-type类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用CSS3选择器:first-of-type 来选择具有给定类名的第一个元素?



代码(http://jsfiddle.net/YWY4L/ ):



  p:first-of-type {color:blue} p.myclass1:first-of-type {color:red} .myclass2: / code> 

 < div& < div>此文本应显示为正常< / div> < p>此文本应为蓝色。< / p> < p class =myclass1>此文本应显示为红色。< / p> < / p>< / div>  


解决方案

不,不可能只使用一个选择器。 :first-of-type 伪类选择类型 div p 等)。使用具有该伪类的类选择器(或类型选择器)意味着如果具有给定类(或具有给定类型)的是其类型中的第一个



不幸的是,CSS不提供:第一类选择器,只选择第一个发生类。作为解决方法,您可以使用这样的:

  .myclass1 {color:red; } 
.myclass1〜.myclass1 {color:/ * default,或继承自父div * /; }

解决方法的说明和插图这里这里


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?

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>

解决方案

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.

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 */; }

Explanations and illustrations for the workaround are given here and here.

这篇关于CSS3选择器:first-of-type类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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