Universal Selector

In CSS the asterisk *, also known as the universal selector, can be used quickly select all elements of a specific type.

Purpose

The universal selector aims to provide a concise way to select and individually style all elements it matches. If used in isolation it will target all elements on the page, this can be useful for tasks like CSS Resets.

CSS
/* Simple reset to remove default browser padding and margin */
* {
padding: 0;
margin: 0;
}

Selection vs Inheritance

While the universal selector may appear similar to other element selectors like html, or body, it's important to recognize that behind the scenes it works quite differently. As the image below attempts to demonstrate using the universal selector is equivalent to writing a CSS rule whose selector includes a comma separated list of all HTML elements that match the selection criteria.

shows that universal selector is the same as writing out a css rule whose selector is a long comma separated list targeting every element specifically

This means it individually selects each matching element and directly sets their properties to the given values. Taking note of this detail is important because this action overrides all inherited values for the properties being set. Let's drive this home with an example.

An Example

In the example below we have a simple HTML page with a card element. What color will the text in the card's <h1> and <p> tags be?

HTML
<!DOCTYPE html>
<html lang="en">
<body>
<div class="card">
<h1>Title</h1>
<p>bUt mUh InheriTeD CoLors</p>
</div>
</body>
</html>
CSS
* {
color: blue; /* Pay attention to this */
}
.card {
color: red; /* and this */
width: 300px;
height: 150px;
background-color: #eee;
border-radius: 2rem;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

If you said blue you're right. In this case the universal selector individually sets the color property of all elements to blue. The next rule in the cascade contains a declaration that sets the color property on our card class to red. If the universal selector wasn't present all of the card's children would inherit color from their parent and the displayed text would be red. However in this case the default inheritance that would have taken place for content of the <h1>, and <p> tags has been overridden, so we're left with blue text.

Codepen Demo

Published: Aug 30th, 2019