Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rule behind "CSS 256 Classes Override One ID"?

Tags:

css

I have came through this situation recently but unable to find 'Why'? Can anyone explain?

See the example below at: http://codepen.io/chriscoyier/pen/lzjqh

like image 722
Jerry Jones Avatar asked Aug 17 '12 09:08

Jerry Jones


People also ask

Can a class override an ID CSS?

An ID selector only takes precedence over a Class selector if they are both used in the same element.

Does class or ID take precedence CSS?

CSS specificity rule Below are the order of specificity rule which has precedence respectively: 1) Inline style: Inline style has highest priority among all. 2) Id Selector: It has second highest priority. 3) Classes, pseudo-classes and attributes: These selectors has lowest priority.

How are the ID and class CSS rules different?

The difference between Class and ID selector The difference between an ID and a class is that an ID is only used to identify one single element in our HTML. IDs are only used when one element on the page should have a particular style applied to it. However, a class can be used to identify more than one HTML element.

Is Id higher than Class CSS?

ID's are more specific than classes and take precedence over them. This is because ID's have to be UNIQUE on every page...so they are by nature very specific. Classes can appear multiple times. Learning how this works is fundamental to coding CSS.


2 Answers

This happens due to a browser limitation, and not a mistake in the spec or how browsers implement it.

The spec says:

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.

Browsers have to store specificity values as integers for the purposes of calculation, and somehow a value of 256 causes an overflow depending on the browser. This usually happens with an 8-bit unsigned integer, whose max value is 255; adding one more causes the class-level specificity to somehow be "upgraded" into an ID-level value, making it equal to the ID in the cascade and thereby overriding it.

like image 153
BoltClock Avatar answered Nov 09 '22 21:11

BoltClock


This is all explained in a article:

extreme-specificity

like image 33
Mark Avatar answered Nov 09 '22 20:11

Mark