css3 之结构性伪类选择器


本篇介绍伪类选择器以及伪元素。

1、类选择器

在 css 中可以使用类选择器把相同的元素定义成不同的样式。比如:

p.left{text-align: left}
 p.rigth{text-align: right}

2、伪类选择器

区别

类选择器和伪类选择器的区别在于,类选择器我们可以随意起名,而伪类选择器是 CSS 中已经定义好的选择器,不可以随意起名

常见的伪类选择器:

a:link{ color: #ff6600 } /* 未被访问的链接 */
 a:visited{ color: #87b291 } /* 已被访问的链接 */
 a:hover{ color: #6535b2 } /* 鼠标指针移动到链接上 */
 a:active{ color: #55b28e } /* 正在被点击的链接 */

3、伪元素选择器

伪元素选择器,针对于 CSS 中已经定义好的伪元素使用的选择器。

使用方法:

选择器:伪元素 {属性:值}

与类配合使用

选择器. 类名:伪元素 {属性:值}

四个伪元素选择器。

1)、first-line 伪元素选择器

first-line 伪元素选择器用于向某个元素中的第一行文字使用样式。

2)、first-letter 伪元素选择器

first-letter 伪元素选择器用于向某个元素中的文字的首字母(欧美文字)或第一个字(中文或者是日文等汉字)使用样式。

3)、before 伪元素选择器

before 伪元素选择器用于在某个元素之前插入一些内容。

4)、after 伪元素选择器

after 伪元素选择器用于在某个元素之后插入内容。

-----------------------------例子



  
    
    伪元素
    
  
  
    

在CSS中,主要有四个伪元素选择器
first-line伪元素选择器用于向某个元素中的第一行文字使用样式。

5、结构性伪类选择器 root、not、empty 和 target

1)、root 选择器

root 选择器将样式绑定到页面的根元素中。

2)、not 选择器

想对某个结构元素使用样式,但是想排除这个结构元素下面的子结构元素,让它不使用这个样式时,我们就可以使用 not 选择器。

3)、empty 选择器

empty 选择器指定当元素中内容为空白时使用的样式。

-----------------------例子



  
    
    not选择器
    
  
  
    

h1标题


1 2 3 4
1 2 4
A B C

4)、target 选择器

target 选择器对页面中某个 target 元素指定样式,该样式只在用户点击了页面中的超链接,并且跳转到 target 元素后起作用。




    
    TARGET
    


A
B
C
D

标题

内容.........

标题

内容.........

标题

内容.........

标题

内容.........

6、选择器 first-child、last-child、nth-child 和 nth-last-child

1)、first-child 选择器

first-child 单独指定第一个子元素的的样式。

2)、last-child 选择器

last-child 单独指定最后一个子元素的的样式。

3)、nth-child 选择器

nth-child(n) 选择器匹配正数下来第 N 个子元素
 nth-child(odd) 选择器匹配正数下来第奇数个子元素
 nth-child(even) 选择器匹配正数下来第偶数个子元素

4)、nht-last-child 选择器

nth-last-child(n) 选择器匹配倒数数下来第 N 个子元素
 nth-last-child(odd) 选择器匹配倒数数下来第奇数个子元素
 nth-last-child(even) 选择器匹配倒数下来第偶数个子元素

7、only-child 选择器

only-child 选择器,只对唯一的子元素起作用。



  
    
    选择器first-child、last-child、nth-child和nth-last-child
    
  
  
    

唯一的:li:only-child

  • 第一个项目

很多的

  • 第1个项目
  • 第2个项目
  • 第3个项目
  • 第4个项目
  • 第5个项目
  • 第6个项目
  • 第7个项目
  • 第8个项目

CSS