<h1>What is scope in CSS?</h1>
<p>
Many people talk about 'scope' in CSS. I want to examine this and try and work out exactly what is meant by this.</p>
<h2>Harry Roberts</h2>
<p>
In this <a href="">article</a> Harry Roberts talks about 'loose selectors'. By this, he means selectors that are overly generic and so can easily be reused elsewhere in the stylesheet by accident.
</p>
<p>According to Roberts, selectors are like variables that exist in the global scope of the stylesheet and have the same name clashing issues that global variables in a programming language have. They can be easily overwritten and can have unintended consequences in other parts of the program.</p>
<p>The problem that Roberts describes is a real one. However, a slight quibble is that selectors are not really like variable names. Selectors can clash even when they are completely different.</p>
Consider the following:
<h2 class="foo">
Hello
</h2>
<pre>
<style>
h2 {
background: red !important;
}
.foo {
background: green;
font-size: 50px;
}
</style>
<h2 class="foo">
Hello
</h2>
</pre>
<p>
The two rule sets' selectors are completely different, yet we still found that the declarations in one of them were overidden by the other.
</p>
<p>I think that selectors are more like functions. They take a selector string and pass back a set of matching elements from the DOM. These functions do though act upon the entire document. We could write them like this:</p>
<pre>
const elements1 = document.querySelectorAll('h2');
const elements2 = document.querySelectorAll('.foo');
</pre>
<p>
Note that the method acts upon the document. Every selector takes as input every element in the document.
</p>
<p>Nor are rule sets like normal variable values. The declarations within a rule set are not automaticaly applied to every element that matches the selector. The cascade in CSS peforms a filtering process which only applies those declarations to a...
CSS
h2 {
background: red !important;
}
.foo {
background: green;
font-size: 50px;
}
pre {
padding: 10px;
border: solid 2px black
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.