权重划分
原文链接:https://note.noxussj.top/?sou...
选择器权重划分代表有多个选择器同时选中同一个元素时,应该以谁的为准,这里就会波及到权重的问题。
现实生活举例
假如你的好敌人小明和路人小红同时掉水里,你先救谁?那你可能会先救小明,因为小明的优先级/权重比拟高。
根底案例
在同一层级下
同一层级代表通过单个选择器间接选中某个元素。
以下案例存在类选择器和 id 选择器,两个选择器同时都选中了 “小明” 这个 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> .person { color: green; } #xiaoming { color: red; } </style> </head> <body> <div class="person" id="xiaoming">小明</div> </body></html>
最终后果是显示了红色的 "小明",id 选择器优先级绝对较高。
其余的权重不须要特意记住,只须要晓得以下前四个优先级即可。
!important > 内联款式 > 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> .box2 { color: green; } .box1 .box2 { color: red; } </style> </head> <body> <div class="box1"> <div class="box2">小明</div> </div> </body></html>
最终后果是显示了红色的 "小明",因为 .box1 .box2 是两层,而 .box1 是一层。
最全面的前端笔记来啦,蕴含了入门到入行的笔记,还反对实时成果预览。小伙伴们不须要在花工夫去写笔记,或者是去网上找笔记了。面试高频发问和你想要的笔记都帮你写好了。反对挪动端和 PC 端浏览,深色和浅色模式。
原文链接:https://note.noxussj.top/?sou...