Cascading part of Cascading Style Sheets • The rules for which CSS rules take precedence over others • However, many web developers struggle to grasp how CSS specificity works
a property that overrides CSS’s normal cascading by making your CSS rule always work • e.g. color: red !important; • I feel like CSS Tricks summarized why devs use !important pretty well:
(or future devs) have to add more !importants .sidebar { background-color: #a066b7 !important; } • CSS becomes difficult to maintain and difficult to make changes because it becomes a labyrinth of !important rules .blog .sidebar { background-color: #e7cdf2 !important; } • Some people don’t understand how to override CSS rules and resort to “!important”
# Classes / Attributes IDs Inline Style # # # • The higher the number, the higher the precedence • If the specificity is the same for multiple selectors, the last selector will apply • Selectors with digits further to the left will always take precedence over selectors with digits further to the right • e.g. A selector with 1 ID will always override a selector with 50 classes
The only way to override it is with another !important and more specific selectors • You can think of it like a 5th digit * { background-color: red !important; } 0 0 0 0 .my-div { background-color: red !important; } 0 0 1 0 #content #sidebar.blog- sidebar > div { background-color: red !important; } 0 2 1 1 1 1 1
no specificity. Neither do selectors such as > (direct child), + (next sibling), ~ (general sibling), etc. • Pseudo-classes (:first-child) also count as classes • The pseudo-class :not has no specificity, but its argument adds specificity • e.g. div.my-div:not(.other-div) – 0, 0, 2, 1
• e.g. "html h1" and "body h1" are both 0, 0, 0, 2, so whichever selector is second will take effect • Styles for directly targeted elements will always take precedence over styles for the parent element (even !important on the parent element styles!) #my-div { background-color: pink; color: blue !important; } h1 { background-color: blue; color: pink; } Pink Text
understand illustrated guide to CSS specificity http://cssspecificity.com/ • Mozilla Developer Network: Specificity https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity • CSS Tricks: Specifics on CSS Specificity https://css-tricks.com/specifics-on-css-specificity/ • CSS Tricks: When Using !important Is the Right Choice https://css-tricks.com/when-using-important-is-the-right-choice/