Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an earlier CSS rule override a later rule?

In my stylesheet, .four-across li defines width: 174px; at line 8806. Below that rule at line 9603, .no-search-results defines width: auto;. However, the 174px rule is overriding an element with .no-search-results. Why would that be?

CSS in Chrome Developer Tools

like image 305
nickh Avatar asked Aug 27 '13 17:08

nickh


3 Answers

You should read about CSS specificity.

.four-across li is more specific than .no-search-results, so it have higher importance level.

Specificity is calculated by counting various components of your css and expressing them in a form (a,b,c,d). This will be clearer with an example, but first the components.

  • Element, Pseudo Element: d = 1 – (0,0,0,1)
  • Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
  • Id: b = 1 – (0,1,0,0)
  • Inline Style: a = 1 – (1,0,0,0)

by Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade

Document order matters only when given specificity is exactly the same. In you example first selector is (0,0,1,1) and second is (0,0,1,0), so the first one overrides the second one, no matter how are they ordered within CSS document.

like image 198
MarcinJuraszek Avatar answered Oct 18 '22 09:10

MarcinJuraszek


Read:

  • Reviewing CSS Style Priority Level

  • Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade

In this case it's because a class and an element type are more specific than just a class, and it's favored over the order.

like image 28
Itay Avatar answered Oct 18 '22 07:10

Itay


Two reasons:

  1. The last rule scanned has precedence over those scanned previously, all else being equal.
  2. The more specific the rule is (two specifiers as opposed to one) the higher the precedence.
like image 1
fred02138 Avatar answered Oct 18 '22 08:10

fred02138