How deep is your selector

What do I mean by selector is too deep? You know how HTML is like a tree, it has levels, parents and children? Let’s say there is a span that is nested in p that is nested in a div with a class of .col that is nested in another div with a class of .row that is nested in .container. HTML would look like this:

1
2
3
4
5
6
7
<div class="container">
<div class="row">
<div class="col">
<p> My two cents on <span>FE</span> topics </p>
</div>
</div>
</div>

If we want to select our span by going through the tree, our CSS might look something like this:

1
2
3
4
5
6
.container .row .col p span {
font-size: 1rem;
font-weight: 400;
letter-spacing: 1.2rem;
color: #bada55;
}

Hm can we be absolutely sure that this is the only place we want to add those styles? We can’t, especially in the large scale commercial project. What if we want to use those same styles and apply them to some other span that is not nested in any of these elements. Or if we want to reuse them on some other element that is not span at all? We simply would not be able to extract these deeply nested styles. We would have to make sure that our HTML always has the same structure as the one above. We would not be able to style <span> in this markup:

1
2
3
4
5
6
7
<footer class="footer">
<div class="row">
<ul class="list">
<li><a href="#"> My two cents on <span>FE</span> topics </a></li>
</ul>
</div>
</footer>

Our CSS is not content agnostic anymore. To avoid this we can use classes which will allow us to reuse them in any markup we want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.span {
font-size: 1rem;
font-weight: 400;
letter-spacing: 1.2rem;
color: #bada55;
}

<div class="container">
<div class="row">
<div class="col">
<p> My two cents on <span class="span">FE</span> topics </p>
</div>
</div>
</div>

<footer class="footer">
<div class="row">
<ul class="list">
<li><a href="#"> My two cents on <span class="span">FE</span> topics </a></li>
</ul>
</div>
</footer>
My two cents are to use class instead of nested selectors.