The broadest possible selector that can be used in CSS, the universal or "wildcard" selector is also the most powerful. Used as a single selector, a wildcard sets absolutely everything to the values you specify. For example:
* { color: red; }
… sets every tag (and as a result, every piece of content, excluding bitmap images) to red. This includes links, headings, paragraphs, table cells, even pseudo-selector states such as :hover
and :visited
.
The universal selector is the CSS equivalent of a neutron bomb, wiping out everything it is applied to. The universal selector also overwrites the usual inheritance rules in CSS. For example, writing this line after the above declaration:
div { color: black; }
…would normally set all text inside div
elements to black; but the previous declaration will overwrite it. You’d need to countermand it by using a variation of the universal selector again:
div * { color: black; }
While setting all text on a website to red isn’t a realistic option for most sites, the selector can also be used as a helpful mini CSS reset at the start of a stylesheet:
* {
border: none;
box-sizing: border-box;
}
This eliminates borders on every element by default, and sizes all containers using the border-box
model (making the sizing of elements much easier). If you’re prepared for more work, you could also reset padding
, margin
, and line-height
at the same time:
* {
border: 0; padding: 0;
line-height: 0;
margin: 0;
box-sizing: border-box;
}
This requires you to rebuild your CSS, but it does have the benefit of allowing you to start from scratch without depending on (or fighting) built-in browser appearence rules for elements in UA stylesheets.
A final note: due to its overwhelming nature, the universal selector can slow browser performance, especially on complex sites with a lot of markup: the stylesheet must apply the rules of the universal selector declaration to every tag before the rest of your CSS takes effect. This should be kept in mind as you optimize the CSS for a site.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.