Applying CSS styles to HTML involves understanding the concepts of the cascade and specificity. The cascade refers to the order in which styles are applied, and specificity determines which styles take precedence when there are conflicting rules. Here's a guide on how to apply CSS styles using cascade and specificity:
-
Cascade:
The cascade is the order in which styles are applied, and it follows a hierarchy. Styles can be inherited, overridden, or merged. Here's the general order:
- User agent styles: Default styles applied by the browser.
- User styles: Styles specified by the user, such as browser extensions or settings.
- Author styles: Styles provided by the web page developer.
-
!important:
Styles marked with
!important
have the highest priority.
-
Specificity:
Specificity is a measure of how specific a selector is in targeting HTML elements. It consists of four components: inline styles, IDs, classes, and elements. The more specific a selector is, the higher its specificity.
-
Inline styles:
Applied directly to an element using the
style
attribute. Highest specificity. -
IDs:
Defined using
#id.
Higher specificity than classes and elements. -
Classes/attributes/pseudo-classes:
Defined using
.class, [attribute], or :pseudo-class.
Intermediate specificity. - Elements: Defined by tag names. Lowest specificity
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Cascade and Specificity</title> <style> /* Author styles */ body { font-family: Arial, sans-serif; color: #333; } h1 { color: blue; } p { font-size: 16px; } /* Specificity example */ .container p { color: red; /* More specific than h1 selector */ } #unique-paragraph { font-weight: bold; /* Higher specificity than .container p */ } /* !important example */ .important-text { color: green !important; /* Overrides other styles regardless of specificity */ } </style> </head> <body> <div class="container"> <h1>Title</h1> <p id="unique-paragraph" class="important-text"> This is a unique paragraph. </p> </div> </body> </html>
-
Inline styles:
Applied directly to an element using the
In this example:
-
body
styles apply to the entire document. -
h1 and p
styles apply to those respective elements. -
The
.container p
selector is more specific than theh1
selector. -
The
#unique-paragraph
selector is more specific than.container p
. -
The
.important-text
class uses!important
, giving it the highest priority.
Understanding the cascade and specificity helps you control the appearance of your web page and handle conflicts in a predictable way.