In-depth understanding of CSS style loading order and override order

code show as below:


height: 100%; 
width: 200; 
position: absolute; 
left: 0; 
border: solid 2 #EEE; 

.current_block { 
border: solid 2 #AE0; 


Looking in some textbooks (w3schools, etc.), it only says that the order of css is "style on element" > "style element on file header" > "external style file", but the priority for multiple identical styles in a style file How to arrange, there is no detailed description. After testing and continuing to search, we know that the priority is as follows: 

1. The more precise the element selector of the style sheet is, the higher the style priority is: 
the style specified by the id selector > the style specified by the class selector > the element type The style specified by the selector 
So in the above example, the style priority of #navigator is higher than the priority of .current_block, even if .current_block is the latest addition, it will not work. 

2. For styles made by the same type of selector, in the style sheet file, the later the priority is higher 
. Note that the later in the style sheet file, the higher the priority, not the order in which the element class appears. For example, .class2 appears after .class1 in the stylesheet: 

copy code
code show as below:

.class1 { 
color: black; 

.class2 { 
color: red; 


When specifying a class for an element, use class="class2 class1" to specify it. At this time, although class1 is specified in the element, it is placed after class2, but because class1 is in front of class2 in the style sheet file, it is still The priority of class2 is higher, and the attribute of color is red instead of black. 

3. If you want to make a style take precedence, you can use !important to specify: 

copy code
code show as below:

.class1 { 
color: black !important; 

.class2 { 
color: red; 


In this case the class will use black instead of red. 

For the problem encountered at the beginning, there are two solutions: 
1. Take the border out of the #navigator and put it in a class .block, and put the .block before .current_block: 

copy code
code show as below:

#navigator { 
height: 100%; 
width: 200; 
position: absolute; 
left: 0; 

.block { 
border: solid 2 #EEE; 

.current_block { 
border: solid 2 #AE0; 


需要默认为#navigator元素指定class="block" 

2. 使用!important: 

复制代码
代码如下:

#navigator { 
height: 100%; 
width: 200; 
position: absolute; 
left: 0; 
border: solid 2 #EEE; 

.current_block { 
border: solid 2 #AE0 !important; 


此时无需作任何其他改动即可生效。可见第二种方案更简单一些。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775572&siteId=291194637