Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Rules to override Style Sheet Rule in CSS
CSS follows a specific hierarchy when multiple styles are applied to the same element. Understanding the cascade and specificity rules helps you control which styles take precedence.
CSS Cascade Priority Order
CSS applies styles based on the following priority order, from highest to lowest:
-
Inline styles - Styles applied directly to HTML elements using the
styleattribute -
Internal stylesheets - Styles defined within
<style>tags in the HTML document - External stylesheets - Styles defined in separate CSS files linked to the HTML document
Example: Style Override Hierarchy
<!DOCTYPE html>
<html>
<head>
<!-- External CSS (lowest priority) -->
<link rel="stylesheet" href="styles.css">
<!-- Internal CSS (medium priority) -->
<style>
p {
color: blue;
font-size: 18px;
}
</style>
</head>
<body>
<!-- Inline CSS (highest priority) -->
<p style="color: red;">This text will be red, not blue</p>
<p>This text will be blue (from internal CSS)</p>
</body>
</html>
CSS Specificity Rules
Beyond the cascade, CSS also uses specificity to determine which rules apply:
-
!importantdeclarations override all other rules - Inline styles have specificity value of 1000
- IDs have specificity value of 100
- Classes and attributes have specificity value of 10
- Elements have specificity value of 1
Comparison Table
| Style Type | Priority Level | Example |
|---|---|---|
| Inline Style | Highest | style="color: red;" |
| Internal CSS | Medium | <style>p { color: blue; }</style> |
| External CSS | Lowest |
p { color: green; } in external file |
Best Practices
- Use external stylesheets for maintainable code
- Avoid inline styles when possible
- Use
!importantsparingly as it makes CSS harder to maintain - Organize CSS with proper specificity to avoid conflicts
Conclusion
CSS follows a clear hierarchy: inline styles override internal styles, which override external styles. Understanding this cascade helps you write more predictable and maintainable CSS code.
Advertisements
