一.全局选择器
可以与任何元素匹配,优先级最低,一般做样式初始化
*{ 属性:value; 属性:value; ..... }
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ color: red; font-size: 40px; } </style> </head> <body> <p>我是一个段落</p> <h1>我是h1标签</h1> </body> </html>
二.元素选择器
HTML文档中的元素, p、b、div、a、img、body 等。
标签选择器,选择的是页面上所有这种类型的标签,所以经常描述 “共性”,无法描述某一个元素的“个性”。
注:
-
所有的标签,都可以是选择器。比如ul、li、label、dt、dl、input、div等
-
无论这个标签藏的多深,一定能够被选择上
-
选择的所有,而不是一个
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> p { color: aqua; font-size: 40px; } span { color: red; font-size: 60px; } </style> </head> <body> <p>我是段落1</p> <h3>我是h3标签</h3> <p>我是段落2</p> <p>我是<span>段落</span>3</p> </body> </html>
三.类选择器
规定用圆点.
来定义,针对你想要的所有标签使用,主要是灵活!
特点:
-
类选择器可以被多种标签使用
-
类名不能以数字开头
-
同一个标签可以使用多个类选择器。用空格隔开
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .color{ color: aquamarine; } .size { font-size: 40px; } </style> </head> <body> <p class="size">我是一个<span class="color">段落</span></p> <h3 class="size">我是h3标签</h3> <h2 class="color size">我是h2标签</h2> </body> </html>
四.ID选择器
针对某一个特定的标签来使用,只能使用一次。 CSS
中的ID选择器
以#
来定义
注意:
-
ID是唯一的
-
ID不能以数字开头
实例: test 这个id被使用了两次,效果一样!但是id选择器就是规定了只给一个标签使用,相当于某个标签的特性!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #test { color: red; font-size: 40px; } </style> </head> <body> <p id="test">我是一个段落</p> <h3 id="test">h3标签</h3> </body> </html>
五.合并选择器
-
语法
选择器1,选择器2...{ 属性:value; 属性:value; .... }
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* 类选择器合并 */ .class1,.class2{ color: aquamarine; font-size: 40px; } /* 元素选择器合并 */ h2,p { color: red; font-size: 50px; } /* id选择器合并 */ #id1,#id2 { color: rebeccapurple; font-size: 50px; } </style> </head> <body> <!-- 类选择器 --> <p class="class1">我是类选择器中的段落1</p> <h2 class="class2">我是类选择器中的h2标签</h2> <!-- 元素选择器 --> <p>我是元素选择器中的段落2</p> <h2>我是元素选择器中的h2标签</h2> <!-- id选择器 --> <p id="id1" class="class1">我是id选择器中的段落3</p> <h2 id="id2" class="class2">我是id选择器中的h2标签</h2> </body> </html>
六.选择器优先级
看完合并选择器源码后,
发现类选择器,元素选择器同时在时,类选择器起效果!
类选择器,id选择器同时在时,id选择器起效果!
故总结优先级得:
行内样式 > ID选择器 > 类选择器 > 元素选择器