常用选择器
id选择器#id
#firstname 选择 id=“firstname” 的所有元素。
类选择器.class
.intro 选择 class=“intro” 的所有元素。
通配符* * 选择所有元素
标签选择器element
p 选择所有 p元素。
并级选择器element,element
div,p 选择所有 div 元素和所有 p 元素。
父子级element element
div p 选择 div元素内部的所有 p元素。
直接子级element>element
div>p 选择父元素为 div 元素的所有 p 元素。
相邻兄弟选择器element+element
div+p 选择紧接在 div 元素之后的所有 p 元素。
属性选择器[attribute]
[target] 选择带有 target 属性所有元素。
属性值选择器[attribute=value]
[target=_blank] 选择 target="_blank" 的所有元素。
选择器的权重规则
权重是什么?
如果一个标签里面又有类又有id选择器的话,标签的渲染会听谁的话呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选择器的权重</title>
<style>
#box {
background-color: red;
}
.box {
background-color: blue;
}
</style>
</head>
<body>
<div class="box" id="box">div1</div>
</body>
</html>
根据渲染结果我们可以得出,它听了id选择器的话。
因为选择器之间的权重不一样,如果选择器之间的css产生冲突,那么权重越大的可以覆盖掉权重小的
但是由于css有三种不同的引入形式(行内,内部,外部)所以根据不同的引入形式,权重也不一样: 行内的权重最重, 内部的权重次之,写在 外部css文件里面的样式权重最低
一、选择器类型
1、ID #id
2、class .class
3、标签 p
4、通用 *
5、属性 [type=“text”]
6、伪类 :hover
7、伪元素 ::first-line
8、子选择器、相邻选择器
二、权重计算规则
第一等:代表内联样式,如: style=””,权值为1000。
第二等:代表ID选择器,如:#content,权值为0100。
第三等:代表类,伪类和属性选择器,如.content,权值为0010。
第四等:代表元素选择器和伪元素选择器,如div p,权值为0001。
通配符、子选择器、相邻选择器等的。如*、>、+,权值为0000。
继承的样式没有权值。
三、比较规则
1,0,0,0 > 0,99,99,99,也就是说从左往右逐个等级比较,前一等级相等才往后比
1, 0 , 0, 0
0, 99 , 99 , 99
!important 的作用是提升优先级,加了这句的样式的优先级是最高的
css3新增常用选择器
:first-of-type
p:first-of-type 选择属于其父元素的首个 p 元素的每个 p 元素。
:last-of-type
p:last-of-type 选择属于其父元素的最后 p 元素的每个 p 元素。
:only-of-type
p:only-of-type 选择属于其父元素唯一的 p 元素的每个 p 元素。
:only-child
p:only-child 选择属于其父元素的唯一子元素的每个 p 元素。
:nth-child(n)
p:nth-child(2) 选择属于其父元素的第二个子元素的每个 p 元素。
:nth-last-child(n)
p:nth-last-child(2) 同上,从最后一个子元素开始计数。
:nth-of-type(n)
p:nth-of-type(2) 选择属于其父元素第二个 p 元素的每个 p 元素。
:nth-last-of-type(n)
p:nth-last-of-type(2) 同上,但是从最后一个子元素开始计数。
:first-child
p:first-child 选择属于父元素的第一个子元素的每个 p 元素。
:last-child
p:last-child 选择属于其父元素最后一个子元素每个 p 元素。
:not(selector)
:not(p) 选择非 p元素的每个元素。