前段时间我去面试一家挺好的公司,面试问的就是 请说出css3中你知道的几种选择器以及他们之间优先级 我就从我工作中常用性进行书写
1.类式选择器
.className{ // . 类名
// 样式声明
}
//例子 选择所有class="parent"的元素
<div class="parent"></div>
.parent{
width:100px;
height:100px;
background: green;
}
2.id选择器
#idName{ // # id值
// 样式声明
}
//例子 选择id="child"的元素
<div id="child"></div>
.child{
width:100px;
height:100px;
background: green;
}
3.通用选择器
- 选中dom页面内所有的元素
*{
pading:0;
margin:0;
}
4.元素选择器
p{} 选择所有<p>元素
5.组合选择器
element,element
div,p{} 选择所有<div>元素和<p>元素
6.后代选择器
element element
div p{} 选择<div>元素内的所有<p>元素
7.子类选择器
div>p{} 选择所有父级是 <div> 元素的 <p> 元素
8.兄弟选择器
element+element
div+p {} 选择所有紧接着<div>元素之后的<p>元素
element~element
div~p{} div后面所有的p元素
9.属性选择器
9.1.[attriBute]
[target] 选择所有带有target属性元素
9.2 [attriBute=value] 属性等于指定值的元素
[target=name] target属性 等于name的元素
9.3 [attribute~=value] 所有属性值中含有 value的值
[target~name] target属性中含有 name的 元素
// 属性选择器 不仅仅是上面的这三种 我只是拿来举例子 因为用的比较少 就不全部拿来说了
10.伪类选择器
10.1. 普通的伪类选择器
element:hover
div:hover{} 鼠标移上div上触发的的样式 离开重新恢复
element:active
a:active 选择活动链接
:focus
input:focus 选择具有焦点的输入元素
:visited
a:visited 选择所有访问过的链接
10.2 结构伪类选择器
:first-child
p:first-child 选择每个p元素是其父级的第一个子元素
:last-child
p:last-child 选择每个p元素是其父级的最后一个子级。
:nth-child(n)
p:nth-child(2) 选择每个p元素是其父级的第二个子元素
10.3 伪类生成器选择器
::after
div:after{content:'',display:'block'}
::before
div:before{content:'',display:'block'}
11
:not(selector)
:not(selector) :not(p) 选择每个并非p元素的元素
工作中常用的选择器 就上面这些了
还有一个很重要的知识就是他们之间的优先级问题
浏览器初始继承样式 优先级 最低 0 是出生的时候带的
标签选择器 优先级 低 1
类,伪类选择器,属性选择器 优先级低 10
id选择器 优先级 中 100
内联样式选择器 高 1000
!important 优先级最高 大于 1000