Continuing from Day 002.
Alright, I’ve cracked what the cascade really is, I think.
When two or more styles want to fight over the same element, the cascade steps in like a referee and says: “Calm down, I’ll decide who wins.”
The cascade resolves conflicts using 6 criteria, in this exact order:
- Stylesheet origin
- Inline styles
- Layer
- Selector specificity
- Scope proximity
- Source order Today, I focused on the first one: Stylesheet origin.
Before we go deeper, here’s a mental anchor to keep things straight:
- Browser - User-agent
- Developer (me) - Author
- End-user (you) - User
Now, Stylesheet origin is all about where the styles come from. The truth is: the CSS I write isn’t the only CSS applied to my page. There are actually three origins:
User-agent styles (the browser’s default)
Author styles (my code)
User styles (whatever magic you do in your own browser using DevTools or some other 'codesorcery')
And here’s the priority:
User styles beat Author styles.
Author styles beat User-agent styles.
User-agent styles are the fallback defaults.
So basically, the browser always starts with its own stylesheet (user-agent). Then I come in with my Author stylesheet and override it. And if you decide to open DevTools and play around, your User styles trump everything.
Example:
If I start with this HTML (no Author style yet):
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header class="page-header">
<h1 id="page-title" class="title">Journey to becoming a CSS Pro</h1>
<nav>
<ul id="main-nav" class="nav">
<li><a href="/">Home</a></li>
<li><a href="/easy">Easy</a></li>
<li><a href="/intermediate">Intermediate</a></li>
<li><a href="/pro" class="featured">Pro</a></li>
</ul>
</nav>
</header>
</body>
</html>
It displays the following, notice something that stands out, the Bullet point.
That is the default style, or the User-agent/Browser style. Some other things you may not have noticed are:
- Large font size of the Heading text "Journey to becoming a CSS Pro"
- Top and Bottom margins of the heading and the list.
- Left padding on the list.
With Author style added:
h1 {
color: #2f4f4f;
margin-bottom: 10px;
}
#main-nav {
margin-top: 10px;
list-style: none;
padding-left: 0;
}
#main-nav li {
display: inline-block;
}
It displays the following, notice that the Margin reduced, Padding and Bullet points removed, and the Colors changed:
The default bullets, margins, and padding disappear, my styles override the browser's.
That's Stylesheet origin in action. First stop on the cascade ladder.
I believe anyone can become a CSS Pro, and therefore I am.
Top comments (0)