CSS 选择器

来源:互联网 发布:阿里云优惠码在哪 编辑:程序博客网 时间:2024/05/19 03:42

选取第一个、最后一个元素

方法一

#op li:last-child{ background: #ff0000;}#op li:first-child{ background: #2B93D2;}

方法二

#op li:first-of-type{ background: #4CAF50;}#op li:last-of-type{ background: #8a8e9c;}

区别满足条件:

[一个满足条件]:
p:nth-of-type(2)表示父标签下的第二个p元素。
[两个满足条件]
p:nth-child(2)表示这个元素要是p标签,且是第二个子元素【结构】,是两个必须满足的条件。

:first-child选择器是css2中定义的选择器 :
匹配的是某父元素的第一个子元素,可以说是结构上的第一个子元素。

:first-of-type选择器是css3中定义的选择器 :
匹配的是该类型的第一个,类型是指什么呢,就是冒号前面匹配到的东西,比如 p:first-of-type,就是指所有p元素中的第一个。这里不再限制是第一个子元素了,只要是该类型元素的第一个就行了,当然这些元素的范围都是属于同一级的,也就是同辈的。

同样类型的选择器 :last-child 和 :last-of-type、:nth-child(n) 和 :nth-of-type(n) 也可以这样去理解。

推荐使用:nth-of-type,不容易出问题,因为页面元素插入其他标签啊什么的是比较常见的。

常用:

#Ulist li:nth-of-type(even){background:#ccc;}  /*选取偶数行*/#Ulist li:nth-of-type(odd){ background:#ccc;}  /*选取奇数行*/#Ulist li:nth-child(2n){background:#ccc;}       /* 选取偶数标签 */#Ulist li:nth-child(2n-1){background:#ccc;}     /* 选取奇数标签 */#Ulist li:nth-child(n+4){background:#ccc;}     /*选取大于等于4标签*/#Ulist li:nth-child(-n+4){background:#ccc;}    /*选取小于等于4标签*/#Ulist li:nth-child(3n+1){background:#ccc;}   /*  3n+1表示“隔二取一” */

CSS 选择相邻兄弟选择器:

如果需要选择紧接在另一个元素后的元素,而且二者有相同的父元素,可以使用相邻兄弟选择器

h1 + p {margin-top:50px; //“选择紧接在 h1 元素后出现的段落,h1 和 p 元素拥有共同的父元素

CSS 选择相邻兄弟选择器
:http://www.w3school.com.cn/css/css_selector_adjacent_sibling.asp
CSS 选择器参考手册
http://www.w3school.com.cn/cssref/css_selectors.asp

0 0
原创粉丝点击