We use cookies to enhance your experience on the site
CodeWorlds

Cascade

The cascade, or "cascading," is a fundamental feature of CSS (Cascading Style Sheets) that plays a key role in determining which styles apply to elements on a web page. The cascade defines how different styles and rules are combined, resolves conflicts between them, and determines which styles will ultimately be applied.

The cascade in CSS is based on three main principles:

  1. Source - Styles can come from various sources, such as inline styles, internal stylesheets, external stylesheets, and user and browser styles. The cascade determines the hierarchy of these sources.

  2. Specificity - Each style rule has a specific specificity based on the selectors used. Specificity helps resolve conflicts when different rules try to apply styles to the same element.

  3. Order - When two or more rules have the same specificity, the cascade considers the order in which the rules are defined. A style placed later in the code takes precedence.

Styles acting on a given element can come from different places:

  • Default browser styles alt text

  • External stylesheet

1<head>
2  <link rel="stylesheet" href="styles.css">
3</head>
  • Internal stylesheet in HTML
1<head>
2  <style>
3    .my-paragraph {
4      color: blue;
5    }
6  </style>
7</head>
  • Inline styles in HTML
1<p style="color: red;">Paragraph content</p>

When one element is affected by styles from different sources on one page, their importance hierarchy increases in the following order:

  1. Default browser settings
  2. External stylesheet
  3. Internal stylesheet
  4. Inline style
  5. !important style - anti-pattern

The display order of elements on the page can be changed by adding the !important directive:

1p {
2  background-color: red !important;
3}

What if we use the same location but a different selector?

Group one - highest priority - ID selector (

#element
) Group two - medium priority - class selector, pseudo-class, attribute (
.element
) Group three - lowest priority - element selector, pseudo-element (
element
)

Selectors

*
,
,
,
>
,
+
,
~
are not taken into account when determining which style takes priority.

Go to CodeWorlds