基本选择器
元素选择器
直接用元素名称做选择
div {
color: red;
}
* {
border: 1px solid rgb(0, 0, 0);
padding: 0px;
margin: 0px;
}
属性选择器
/* 有index属性的元素 */
div[index] {
color: blue;
}
/* index属性为某一值的 */
div[index=10] {
color: red;
}
/* 有index属性,并且值包含某一值 */
div[index*="add"] {
color: yellow;
}
/* 有index属性,并且值 开头 包含某一值 */
div[index^="add"] {
color: yellow;
}
/* 有index属性,并且值 结尾 包含某一值 */
div[index$="add"] {
color: yellow;
}
id选择器
#id_value {
color: blue;
}
class选择器
.class_value {
color: brown;
}
特例:结合选择器
p.class_value {
color: red;
}
p#id_value {
color: blue;
}
.class_value#id_value {
color: brown;
}
包含选择器
selector1 selector2 {
color:red;
}
子选择器
div>p {
color: red;
}
兄弟选择器
selector1~selector2 {
color: blue;
}
选择器组合
selector1, selector2, selector3 {
color: blue;
}
伪元素选择器
首字母
/* ::first-letter只能用于块级元素 */
div::first-letter {
color: red;
}
首行
/* ::first-line只能用于块级元素 */
div::first-line {
color: purple;
}
在前边插入 ::before
div::before {
content: "插入的内容";
}
在后面插入 ::after
div::after {
content: "插入的内容";
}
伪类选择器
结构性伪类选择器
:nth-child() :nth-last-child() :first-child :last-child 所有的子元素的
ul li:nth-child(even) {
background-color: blue;
}
/* 括号里可以是数字,代表是第几个元素
也可以是英文单词 odd 奇数 even 偶数 的元素
也可以是数学表达式 2n+1 (n从1开始的正整数)
找第一个元素可以写成 :first-child
:nth-child(1)
找最后一个元素 :nth-last-child(1)
:last-child
*/
table tr:nth-last-child(odd) {
background-color: green;
}
:nth-of-type() :first-of-type :last-of-type :nth-last-of-type() 子元素同类型的
ul li:nth-of-type(1) {
color: red;
}
/* 找的是li同类型下的第一个 */
ul li:first-of-type(1) {
color: blue;
}
/* 同上 */
ul li:nth-last-of-child(1) {
color: brown;
}
/* 找的是同类型最后一个 */
UI状态选择器
:hover 鼠标悬停状态
input:hover {
background-color: red;
}
:focus 焦点状态
input:focus {
background-color: blue;
}
:checked 选中状态
input:checked {
box-shadow: 3px 3px 10px black;
}
其他伪类选择器
:not() 过滤掉某些元素
ul li:not(.java) {
background-color: green;
}
选择器的优先级规则
1、选择器写的越准确优先级越高
2、优先级高低 id选择器 > class选择器 > 元素选择器
3、同级别长度下,CSS代码按照顺序执行,后边的效果会把前边的覆盖
4、终极规则:以上规则适用大部分场景,特殊场景不适用自行测试