Skip to content

CSS selectors you should code without

Sara Vieira's recent post on webdesignerdepot titled "10 CSS selectors you shouldn't code without" is well-intended but starts off on the wrong foot.

The problem lies with selector number one on the list: the universal selector (*).

The * selector may be the one you remember most easily but it’s often underused. What it does is style everything on the page and it’s great for creating a reset and also for creating some page defaults like the font family and size you wish to have.

It's "underused" because it's generally an inappropriate selector to use. It's not "great for creating a reset" nor is it any good for creating page defaults. The problem is that any styles applied via the * may break the automatic inheritance of styles between elements.

Take, for example, this simple markup:

<div>
  <p>Lorem ipsum</p>
</div>

If you were to style it using:

div {
  font-size: 20px;
}

you can expect the font-size of the paragraph to be 20px because it inherits the font-size of its wrapping elements.

However, if you were to add in the * to "create some page defaults"…

* {
  font-size: 100px;
}
div {
  font-size: 20px;
}

The paragraph will have a font-size of 100px. This is absurd. It would be excessive to have to override the * styles everywhere they're not desired, especially as it would needlessly increase the specificity of the selectors on the page. Continuing off the last example, getting the desired effect would require writing an additional style:

* {
  font-size: 100px;
}
div {
  font-size: 20px;
}
div * {
  font-size: 20px;
}

but of course, adding this additional style would cause specificity creep as each subsequent override would have to be overridden when their children need to have different inherited styles. This won't scale for large sites with many CSS components and widgets as there will be too many combinations that will need to be tested to be absolutely certain that things are rendering correctly.

Save yourself the hassle and avoid the * selector.