Wednesday, June 9, 2010

Cascade Order

I’m reading a book “Pro.CSS.and.HTML.Design.Patterns”, as I found so many wired things when using CSS, and I think this book may be helpful for me. and I post some of patterns in the book while learning.

CSS Selector Priority
As a CSS rule(like border:1px solid blue) may be assigned to an element multiple times, we must understand which one will effect the element style, so the following are rules, the priority is from high to low:
  1. !important this has the highest priority, when a rule comes with this, it’s the boss.
  2. style on element here style is the HTML element attribute, like <p style=“margin:2px”/>
  3. ID, again ID is the id of a HTML element. like <div id=“css”/>, then you can use #css to define CSS rules for this div.
  4. CSS class, like .cssClass{...}, also including the pseudo, like .cssClass:after{...}, they have the same priority
  5. HTML element like p, div, br .etc
  6. * this is the universal selector, you can write CSS like this *{padding:1px}, then it applies to every HTML element
Most of time, we use class and ID selectors, but I think class selector is enough, which is at forth priority. especially when I started to use JQuery and JQuery UI, it’s a bad idea to use ID as a CSS selector. as in the HTML page, there may be many elements have the same ID but different element and/or usage, and when you collaborate with others, a good idea is to use multiple class selectors to find an element or apply rules.

Sometimes, you may use a combination of several selectors, for example, #css .cssClass .button{...}, or #css2 .cssClass p {...}. at this time, the one has higher priority when it has more selectors of a higher priority. so in the above example, the first one win, as both of them have ID selector, but the first one has two class selectors, and the second has only one class selector.

Location Priority
What if both selectors have the same number and level of selectors? they’er further prioritized by location. here are the rules, from high priority to low:
  1. <style> in HTML <header>
  2. @import within <style>
  3. <link>
  4. @import within a CSS file attached by <link>
  5. CSS file attached by an end user? how? don’t understand :(
  6. default CSS supplied by a browser
when multiple stylesheets are attached or imported at the same level, stylesheet attached later override stylesheets attached previously.

No comments: