在项目中,使用css选择器选择html标识符进行样式绑定,但各个选择器的优先级会影响css样式的绑定,在不熟悉选择器特性的情况下,很容易被其他选择器覆盖,又非常迷惑,最后可能很暴躁地加了!important 就草草了事,但是维护性比较差。搞清楚css优先级特性对于需求开发非常重要!
阅读了一篇不错的文档 ,结合实践操作的学习笔记。
选择器
- 元素选择器
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
/* <p> elements that don't have a class `.fancy` */
p:not(.fancy) {color: green;}
/* Elements that are not <p> elements */
body :not(p) {text-decoration: underline;}
/* Elements that are not <div> and not <span> elements */
body :not(div):not(span) {font-weight: bold;}
/* Elements that are not <div>s or `.fancy` */
body :not(div, .fancy) {text-decoration: overline underline;}
/* Elements inside an <h2> that aren't a <span> with a class of `.foo` */
h2 :not(span.foo) {color: red;}
- 类选择器
选择方法
.container div.foo {}
.foo.foo1 {}
<div class="container">
<div class="foo foo1" /> 选择元素
</div>
/* <a title=""> 元素包含title属性 */
a[title] {color: purple;}
/* <a href="https://example.org"> */
a[href="https://example.org"]{color: green;}
/* <a href="xxx.example"> href属性包含example */
a[href*="example"] {font-size: 2em;}
/* <a href="xxx.org"> href属性结尾是.org */
a[href$=".org"] {font-style: italic;}
/* <a class="xxlogo"> 有class属性包含logo */
a[class~="logo"] {padding: 2px;}
- 伪类选择器
- Id选择器
- 子类、兄弟选择器
// 兄弟选择器 只会该元素后的兄弟
[title=flower] + p{
color:red;
}
// 兄弟选择器 只会该元素后的所有兄弟
[title=flower] ~ p{
color:red;
}
//子类选择器
div>p{
color:red;
}
<div>
<p >All images with the title attribute containing the word "flower" get a yellow border.</p>
<p title="flower">All images with the title attribute containing the word "flower" get a yellow border.</p>
<p >All images with the title attribute containing the word "flower" get a yellow border.</p>
</div>
选择器优先级
引入方式
外部引用css文件<内部style<行内选择器;
选择方式
- 全局选择器
*是最低优先级;!important属性有最高优先级;
- 伪类选择器有最高的特异性;
- 子类或者兄弟选择器(>,~,+)没有特异性;
- css代码写在后面的会把前面优先级相同的样式覆盖
使用十进制的方法计算选择器的优先级
标签选择器
p {}; /**0,0,0,1**/
span {}; /**0,0,0,1**/
p span {}; /**0,0,0,2**/
p > span {}; /**0,0,0,2**/
div p > span {}; /**0,0,0,3 (1+2=3)**/
类选择器
.name {} /**0,0,1,0**/
.users .name {} /**0,0,2,0**/
[href$='.pdf'] {} /**0,0,1,0**/
:hover {} /**0,0,1,0**/
:not(foo) {} /**0,0,1,0 伪类选择器**/
.name {} /**0,0,1,0**/
.name.name {} /**0,0,2,0**/
.name.name.name {} /**0,0,3,0**/
标签选择器&类选择器
div .name {} /**0,0,1,1**/
a[href$=".pdf"] /**0,0,1,1**/
.pictures img:hover /**0,0,2,1 (.picture + :hover = 2)**/
id选择器
#name {} /**0,1,0,0**/
.use #name {} /**0,1,1,0**/
#name span {} /**0,1,0,1**/
行内选择器
<p style="color:red"></p> //1,0,0,0
致谢🙏
小菜鸡的笔记分享,欢迎各位大佬批评指正。