【HTML5学习笔记】17:CSS选择器 下

来源:互联网 发布:陈华伟 知乎 编辑:程序博客网 时间:2024/06/03 15:25

伪类选择器可以分为四种:结构性伪类、UI伪类、动态伪类、其它伪类。

伪类都需要加上前置的选择器来限制范围。



结构性伪类选择器

根据元素在文档中的位置选择元素,这类元素都有一个前缀(:)。

1.根元素选择器

匹配文档中的根元素,很少使用,因为总是匹配<html>元素。

:root{

}

2.子元素选择器

匹配第一个/最后一个子元素等,如匹配第一个子元素。

ul>li:first-child{

}

此外还有last-child,only-child(独生子子元素),only-of-type(唯一类型子元素)

3.:nth-child(n)系列

匹配第n个子元素。

ul>li:nth-child(2){

}

此外还有nth-last-child(n)从后往前数n个,nth-of-type(n)特定元素的第n个子元素,nth-last-of-type(n)特定元素的倒数第n个子元素。

UI伪类选择器

根据元素的状态匹配元素,主要用来匹配表单里的控件。

1.enabled和disabled

分别匹配启用的和禁用的元素。

input:enabled{

}

2.checked和default

分别匹配选定的和默认(一组类似元素中的默认)的元素,注意两者不冲突。

input:checked{

}

4.valid和invalid

分别匹配输入验证合法与不合法显示时选择的元素。

input:valid{

}

5.required和optionall

分别匹配必写的和不是必写的。

input:required{

}

动态伪类选择器

动态伪类选择器根据条件的改变选择元素,常用在鼠标点击、悬停等。

 

1.link和visited

分别匹配访问过的和未访问过的超链接。

a:link{

}

2.hover和active

匹配鼠标悬停和激活(按住不放)的超链接。

a:active{

}

3.focus

匹配获得焦点的文本框。

input:focus{

}

其它伪类选择器

1.not

反选。

a:not([href*="baidu"]){

}

2.empty

匹配没有任何内容的元素。

可以前置的具体元素:empty{

}

3.target

定位到锚点时,选择此元素。

可以前置的具体元素:target{

}


*测试代码

<!DOCTYPE html><html lang="zh-cn"><head><title>CSS选择器 下</title><meta charset="utf-8"><link rel="stylesheet" type="text/css" href="style.css"></head><body><ul><li>我是儿子</li><li>我是儿子</li><li>我是儿子</li><li>我是儿子</li></ul><div><p>我是段落</p><span>我不是段落</span></div><div><p>我是段落</p><p>我是段落</p></div><form><input type="text" disabled><input type="text"><input type="checkbox"><input type="checkbox" checked><input type="checkbox"></form><form><input type="text" required><input type="email" required><button>提交</button></form><a href="http://www.baidu.com">百度</a></body></html>

@charset "utf-8";/*根元素选择器*/:root{border: 1px solid red;}/*子元素选择器*/ul>li:first-child{color: red;}div>p:only-of-type{color: brown;}/*:nth-child(n)*/ul>li:nth-child(2){color: green;}/*UI选择器*/input:enabled{border: 1px solid black;}input:checked{display:none;}input:valid{border: 1px solid green;}input:invalid{border: 1px solid red;}input:required{background: yellow;}/*动态伪类选择器*/a:link{color: pink;}a:visited{color: blue;}a:hover{color: green;}a:active{color: brown;}input:focus{border: 2px solid orange;}

运行结果: