总结起来很简单:对于一个元素
1.本身没有样式修饰,它会怎么做呢?search! 所以
第一个原则:就近原则,找到离自己最近的祖先元素继承样式
2.本身有样式
2.1 内嵌样式(style)>内联样式表>外联样式表 这点没什么好说的
2.2 当涉及到多个选择器修饰的时候,有优先级顺序:内嵌样式>id>class>标签
举个栗子吧,就是 先比较id个数,在以此类推,具体看demo
https://jsfiddle.net/y0a14gqv/
2.3 !important 最无敌 记住这点就可以了!
======================================================
10/24/
重新看了之前的文章,嗯,我的确是个脑细胞比较简单 的人哈哈...
不过这也是我的性格所致,把自己所想的清楚表达出来,就很满足。
今天看了mdn的文档,里面提及了css优先级,有点意思的是,我之前面试被提及优先级一律按照上诉解决,当然我觉得也没多大碍,如果能说出官方文档的定义,
自然给人感觉牛逼不少,所以还是吸收一下。
一下是原文:
Calculating a selector's specificity
A selector's specificity is calculated as follows:
- count the number of ID selectors in the selector (= a)
- count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
- count the number of type selectors and pseudo-elements in the selector (= c)
- ignore the universal selector
Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
Examples:
* /* a=0 b=0 c=0 -> specificity = 0 */ LI /* a=0 b=0 c=1 -> specificity = 1 */ UL LI /* a=0 b=0 c=2 -> specificity = 2 */ UL OL+LI /* a=0 b=0 c=3 -> specificity = 3 */ H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 11 */ UL OL LI.red /* a=0 b=1 c=3 -> specificity = 13 */ LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */ #x34y /* a=1 b=0 c=0 -> specificity = 100 */ #s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 101 */
挺好理解的就不多说,有几个概念还没想清楚,
pseudo-classes
pseudo-elements
以上这两个
===============================
发觉做网站离不开对css深刻的理解,废话少说,我不时的摘录点:
<p class="class1 class2 class3">something</p>
css代码
.class1{
color: #000;
}
.class2{
color: red;
}
.class3{
color: blue;
}
结果显示:字体颜色为蓝色,class会向前覆盖