Title
Text
In CSS, many rules can apply to the same element.
👉 Example problem:
p {
color: green;
}
p {
color: blue;
}
❓ Which color will be used?
👉 This is called a conflict
Cascade = system that decides which CSS rule wins
When multiple rules apply:
👉 Browser uses:
p {
color: blue;
background-color: orange;
}
p {
color: teal;
}
👉 Result:
Each selector has a weight (priority)
👉 The higher the weight → the stronger the rule
| Rank | Selector | Weight |
|---|---|---|
| 1 | Inline styles | 1000 |
| 2 | ID (#id) | 100 |
| 3 | Class (.class), pseudo-class | 10 |
| 4 | Element (p, div) | 1 |
p {
color: green; /* 1 */
}
section > p {
color: orange; /* 2 */
}
👉 Winner: section > p (more specific)
p {
color: green;
}
ul p {
color: orange;
}
👉 orange wins (more elements in selector)
.post-title {
color: green;
}
.post > .post-title {
color: orange;
}
👉 orange wins (more specific)
a {
color: green;
}
.post-link {
color: orange;
}
a.post-link {
color: blue;
}
.post > a.post-link {
color: brown;
}
👉 Winner: brown (highest specificity)
.post-title {
color: green;
}
#title {
color: orange;
}
👉 Winner: #title (ID is stronger)
👉 This overrides everything
If specificity is the same → 👉 last rule wins
a {
color: teal;
}
a {
color: brown;
}
a {
color: orange;
}
👉 Final: orange
Forces a rule to win
p {
color: orange !important;
}
p#id {
color: blue;
}
👉 Winner: orange
❌ Avoid using !important
Use only:
color: orange !important;
.post > div > ul > li > a
👉 too complex
Use classes
.post > h1 { }
.post > p { }
❌ Not flexible
.post > .title { }
.post > .text { }
✔ Better
.post-title { }
.post-text { }
.post-link { }
✔ simple
✔ scalable
✔ readable
Child elements get styles from parent
.post {
color: green;
}
👉 All text inside becomes green
Title
Text
👉 both inherit color
Not all properties are inherited
.post {
color: green;
}
a {
color: blue;
}
👉 link stays blue
Forces inheritance
.post-link {
color: inherit;
}
👉 link becomes same as parent
Uses current text color
.link {
color: red;
border: 1px solid currentColor;
}
👉 border = red
.post {
color: green;
}
.post-link {
color: currentColor;
}
👉 link = green
👉 Cascade = system that resolves conflicts
👉 Priority:
👉 If equal → last wins
👉 !important → overrides everything (avoid)
👉 Inheritance → children get styles
👉 inherit → copy parent value
👉 currentColor → use current color
👉 Use simple class selectors
👉 Avoid complex selectors
👉 Avoid !important