CSS Inheritance & Specificity
Understanding how CSS styles are applied and which ones take precedence
Lowest Priority
Browser Default Styles
Low Priority
External Stylesheets (Linked CSS)
Medium Priority
Internal Styles (Header Style Tags)
High Priority
Inline Styles
Highest Priority
!important Declarations
Inheritance Example
Text properties are inherited
<div style="color: blue; font-size: 16px;">
Parent element
<div>Child inherits color and font-size</div>
</div>
Box properties are NOT inherited
<div style="border: 1px solid black; padding: 10px;">
Parent element with border and padding
<div>Child does NOT inherit border or padding</div>
</div>
Specificity Example
ID selector beats class selector
#myElement { color: red; } /* Specificity: 0,1,0 */
.myClass { color: blue; } /* Specificity: 0,0,1 */
/* Text will be RED */
Class selector beats element selector
div { color: blue; } /* Specificity: 0,0,1 */
.special { color: red; } /* Specificity: 0,0,1 */
/* But .special wins because it's defined later */
Specificity Values
Selector Type | Example | Specificity Value | Explanation |
---|---|---|---|
Inline Styles | style="color: red;" | 1,0,0,0 | Highest specificity (after !important) |
ID Selectors | #header | 0,1,0,0 | One ID selector |
Class Selectors | .nav-item | 0,0,1,0 | One class, pseudo-class or attribute selector |
Element Selectors | div | 0,0,0,1 | One element selector or pseudo-element |
Universal Selector | * | 0,0,0,0 | No specificity |
No comments:
Post a Comment