css3 之前的基本选择器:
通配符选择器、元素选择器、类选择器、ID选择器、后代选择器。
css3 新增基本选择器:
子元素选择器、相邻兄弟元素选择器、通用兄弟选择器、群组选择器
子元素选择器 - 只能选择某元素的子元素(不包含所有后代,至选择下一代)
父元素 > 子元素
相邻兄弟元素选择器 - 可以选择在一个元素后的元素,而且它们具有一个相同的父元素
元素 + 兄弟元素
通用兄弟选择器 - 选择某个元素后面的所有兄弟元素,他们具有一个相同的父元素
元素 ~ 后面的所有兄弟元素
群组选择器 - 多个选择器放一起,使用同一样式
元素1,元素2,元素3
属性选择器
可以指定元素的某个属性,或者可以同时指定元素的某个属性和其对应的属性值。
- 元素【属性】
<!DOCTYPE html>
<html>
<head>
<title>css3</title>
<meta charset="utf-8">
<style type="text/css">
a[href] {text-decoration: none;}
</style>
</head>
<body>
<div>
<a href="#">attribute</a>
</div>
</body>
</html>
- 元素【属性=“值”】
<!DOCTYPE html>
<html>
<head>
<title>css3</title>
<meta charset="utf-8">
<style type="text/css">
a[href] {text-decoration: none;}
a[href="#"] {color: red;}
</style>
</head>
<body>
<div>
<a href="#">attribute</a>
<a href="none.html">attribute</a>
</div>
</body>
</html>
- 元素【属性~=“值”】
属性包含某个值的所有元素
- 元素【属性^="值"】
属性值,以“值” 开头的所有元素
- 元素【属性$="值"】
属性值,以“值” 结尾的所有元素
- 元素【属性*="值"】
属性值,包含字符串“值” 的所有元素
- 元素【属性|="值"】
属性值,以“值”的所有元素 或者“值-”开头的所有元素
动态伪类选择器
这些伪类,并不存在于html 中,只有当用户和网站交互时,才能体现出来。
锚点伪类 :link , :visited.
用户行为伪类 :hover , :active , :focus ,
UI 元素状态伪类
“:enabled” , “:disabled” , “:checked”
结构类选择器( :nth 选择器)
选择方法:
:first-child, :last-child, :nth-child, :nth-last-child, nth-of-type, :nth-last-of-type,
:first-of-type, :last-of-type, :only-child, :only-of-type, :empty.
- Element:first-child
选择属于其父元素的首个子元素的每个Element元素
- Element:nth-child(N)
选择属于父元素的第N个子元素
- Element:nth-child(2n)
选择属于父元素的第偶数个子元素
- Element:nth-child(2n+1)
选择属于父元素的第奇数个子元素
同理,括号中可以是3n,4n,3n+1,3n-1,...(自变量是n就行)
- Element:nth-child(odd)
选择属于父元素的第奇数个子元素
- Element:nth-child(even)
选择属于父元素的第偶数个子元素
- Element:nth-last-child(N)
选择属于父元素的倒数第N个子元素
- Element:nth-of-type(N)
选择属于父元素的特定类型的(所有)第N个子元素
- Element:only-child
选择属于父元素的唯一的子元素的所有元素
- Element:only-of-type
选择属于父元素的特定类型的且唯一的子元素的所有元素
- Element:empty
选择没有子元素的所有对应Element元素
否定选择器
父元素:not(Element/selector) 选择匹配父元素中非指定元素/选择器的每个元素
<!DOCTYPE html>
<html>
<head>
<title>sdg</title>
<style type="text/css">
*{margin:0;padding:0;border:none;}
a {text-decoration: none;color: #333;font-size: 14px;display: block;float: left;width: 100px;height: 30px;}
nav{width: 800px;margin: 0 auto;}
nav > a:not(:last-of-type){
border-right: 1px solid red;
}
</style>
</head>
<body>
<nav>
<a href="#">first</a>
<a href="#">second</a>
<a href="#">third</a>
<a href="#">fourth</a>
<a href="#">fifth</a>
</nav>
</body>
</html>