Skip to main content

CSS Nesting and Targeting Elements

Nesting​

To avoid specificity wars, keep nesting to a minimum. The flatter the specificity, the more maintainable the CSS is. We want our elements and components to be as independent and modular as possible. As a general rule do not exceed over three nested elements. This will also help improve readability.

Ex:

//Bad

.block .block__element-1 {
background-color: #f2f2f2;
position: relative;
.block__element-2 {
position: absolute;
.block__element-3 {
background-color: #efefef;
color: #000;
}
}
}


//Good

.block {
.block__element-1 {
background-color: #f2f2f2;
position: relative;
}
.block__element-2 {
position: absolute;
}
.block__element-3 {
background-color: #efefef;
color: #000;
}
}

Targeting​

If you need to apply styles to an element, give the element a class and target that selector in the stylesheet. Avoid targeting HTML tags. If you do target tags, you are creating global styles to be applied to every instance of that tag site-wide or within the specified container. At scale, this is not always ideal. You would not be able to add another instance of that tag without inheriting those styles. In addition, it limits the flexibility of your markup. For example, you are targeting an <a> tag in the CSS but someone changes the markup from an <a> tag to a <button>. Your styles are broken without ever touching a selector or stylesheet.

Ex:

//Bad

.block {
ul {
list-style: none;
margin: 0;
padding: 0;
}
a {
color: blue;
text-decoration: underline;
}
}

//Good

.block {
.block__list {
list-style: none;
margin: 0;
padding: 0;
}
.block__link {
color: blue;
text-decoration: underline;
}
}