Tuesday, August 19, 2025

CSS Inheritance & Specificity

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

Key Points to Remember

•CSS follows a cascading order where later rules override earlier ones of the same specificity •Specificity determines which CSS rule is applied when multiple rules conflict •Inline styles have higher specificity than styles defined in style tags or external sheets •Use the !important declaration sparingly as it overrides all other declarations• •Not all CSS properties are inherited (e.g., borders, margins, padding) •You can force inheritance with the inherit value for any CSS property

No comments:

Post a Comment

Statistical View of Entropy Statistical View of Entropy Understand...