网络编程
位置:首页>> 网络编程>> 网页设计>> 30个最常用css选择器解析(7)

30个最常用css选择器解析(7)

作者:iiduce  发布时间:2011-06-16 20:36:37 

标签:css选择器,css,浏览器

28. X:only-child


div p:only-child {
      color: red;
   }


这个伪类用的比较少。在上面例子中匹配的是div下有且仅有一个的p,也就是说,如果div内有多个p,将不匹配。


<div><p> My paragraph here. </p></div>

<div>
      <p> Two paragraphs total. </p>
      <p> Two paragraphs total. </p>
</div>


在上面代码中第一个div中的段落p将会被匹配,而第二个div中的p则不会。

兼容浏览器:IE9+、Firefox、Chrome、Safari、Opera

29. X:only-of-type

li:only-of-type {
      font-weight: bold;
   }

这个伪类匹配的是,在它上级容器下只有它一个子元素,它没有邻居元素。例如上面代码匹配仅有一个列表项的列表元素。

兼容浏览器:IE9+、Firefox、Chrome、Safari、Opera

30. X:first-of-type

:first-of-type伪类与:nth-of-type(1)效果相同,匹配出现的第一个元素。我们来看个例子:

<div>
      <p> My paragraph here. </p>
      <ul>
         <li> List Item 1 </li>
         <li> List Item 2 </li>
      </ul>
      <ul>
         <li> List Item 3 </li>
         <li> List Item 4 </li>
      </ul> 
  </div>

在上面的html代码中,如果我们希望仅匹配List Item 2列表项该如何做呢:

方案一:

ul:first-of-type > li:nth-child(2) {
      font-weight: bold; 
  }

方案二:

p + ul li:last-child {
      font-weight: bold;
   }

方案三:

ul:first-of-type li:nth-last-child(1) {
      font-weight: bold;
   }

兼容浏览器:IE9+、Firefox、Chrome、Safari、Opera。

总结

如果你正在使用老版本的浏览器,如IE 6,在使用上面css选择器时一定要注意它是否兼容。不过,这不应成为阻止我们学习使用它的理由。在设计时,你可以参考浏览器兼容性列表,也可以通过脚本手段让老版本的浏览器也支持它们。

另一点,我们在使用javascript类库的选择器时,例如jquery,要尽可能的使用这些原生的css3选择器,因为类库的选择器引擎会通过浏览器内置解析它们,这样会获得更快的速度。

原文:http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com