码迷,mamicode.com
首页 > 其他好文 > 详细

伪类选择器:first-child和:nth-child()和:first-of-type

时间:2017-06-26 19:05:39      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:ref   round   type   highlight   css   class   标签   script   head   

x:first-child和x:nth-child(1)功能一样,首先选中的是x元素,并且x元素必须是它父元素的第一个子元素,选择器才成立,否则不能选中。其中x也可以是选择器。由此看出nth-child功能强劲,完全可以代替first-child的功能。

x:first-of-type,选择x元素的父元素的首个 x元素,但x不一定是它父元素的第一个子元素,x也不一定是标签选择器,也可以是id选择器、类选择器等。

<!DOCTYPE html>
<html>
<head>
<style> 
p:first-of-type
{
background:#ff0000;
}
/*body的第一个子元素是h1不是p,但body的第一个p子元素是存在的,所以first-of-type能选中,如果换成firs-child或者nth-child(1)就不行了*/

</style>
</head>

<body>
<h1>这是标题</h1>
<p>这是第一个段落。</p>
<p>这是第二个段落。</p>
<p>这是第三个段落。</p>
<p>这是第四个段落。</p>

</body>
</html>

  http://www.w3school.com.cn/cssref/css_selectors.asp

伪类选择器:first-child和:nth-child()和:first-of-type

标签:ref   round   type   highlight   css   class   标签   script   head   

原文地址:http://www.cnblogs.com/qdog/p/7081728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!