CSS scope might not be what you think it is

by Richard Hunter

HTML

<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>

&lt;style>
  h2 {
    background: red !important;
  }

  .foo {
    background: green;
    font-size: 50px;
  }


&lt;/style>
&lt;h2 class="foo">
  Hello
&lt;/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
}