0
0
CSSmarkup~5 mins

Importance of order in CSS

Choose your learning style9 modes available
Introduction

Order in CSS matters because later styles can change or override earlier ones. This helps control how your webpage looks.

You want to change the color of a button after setting its size.
You need to fix a style that is not showing because another style is stronger.
You want to add a special effect only on some parts of your page.
You are using multiple CSS files and want to make sure your styles apply correctly.
You want to override default browser styles with your own.
Syntax
CSS
selector {
  property: value;
  /* Later properties or selectors can override earlier ones */
}
CSS reads styles from top to bottom, so the last matching rule wins if there is a conflict.
More specific selectors override less specific ones, but order still matters when specificity is equal.
Examples
The second p style changes the text color to red because it comes after the blue one.
CSS
p {
  color: blue;
}
p {
  color: red;
}
The green background shows because the second rule overrides the first one.
CSS
.box {
  background: yellow;
}
.box {
  background: green;
}
The font size becomes 3rem and the text bold because the second rule comes later.
CSS
h1 {
  font-size: 2rem;
}
h1 {
  font-size: 3rem;
  font-weight: bold;
}
Sample Program

The first style sets the paragraph text to blue and size 1.5rem. The second style changes the color to red because it comes later. So the text appears red with size 1.5rem.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Order Example</title>
  <style>
    p {
      color: blue;
      font-size: 1.5rem;
    }
    p {
      color: red;
    }
  </style>
</head>
<body>
  <p>This text will be red, not blue.</p>
</body>
</html>
OutputSuccess
Important Notes

Always write your CSS in the order you want it to apply.

Use browser developer tools to see which styles are active and which are overridden.

Remember that specificity and order together decide which style wins.

Summary

CSS order controls which styles apply when there are conflicts.

Later styles override earlier ones if they have the same specificity.

Writing CSS in the right order helps you design your page exactly as you want.