Using the CSS Star Selector to Zero Out Margins and Paddings

You can run over default browser styles with * { margin: 0; padding: 0; }, but be cautious.

Jonathan Saring
Bits and Pieces

--

A simple Google search for “css star selector” shows alarming results.

The * selector matches all elements in the DOM. In fact, you’re already using the star selector without knowing it. When you use other selectors like class or element, they already imply the star selector. So this:

ul {}

The parser really sees this.

* ul {}

Now let’s take a second to look at these CSS lines.

* {
margin: 0;
padding: 0;
}

What this code does is to run over, like an elephant, every default style on the page. This can be useful as sometimes different browsers have different default stylings for different elements. And, because sometimes you just want to define everything yourself.

There are elegant and scalable ways to reset styles. One example is to use a library like normalize.css for building a large website.

But sometimes you just want it quick and dirty. Or, sometimes you just want to reset things for debugging or development purposes.

And if you want to go all out, you can add that border and outline should also be at zero. It looks like this.

* {
margin: 0;
padding: 0;
border: 0;
outline: 0;
}

But be warned that there are two potential downsides to this technique.

  1. Sometimes it can cause performance issues. Steve Souders wrote this beautiful article explaining the performance damage of star selectors.

2. You might very well end up finding yourself resetting default styles that you don’t really want to reset, which greatly varies between different elements on different browsers (such as the submit button for example. So be cautious.

That’s it for now. Please feel free to comment below and suggest your own takes on working with the star selector to run over everything else.

Until next time, Cheers.

Tip:

When creating beautiful components in React, use Bit to extract and share components to the cloud. You can reuse components in all your different projects, sync changes, and share them with your team. Very useful.

--

--

I write code and words · Component-driven Software · Micro Frontends · Design Systems · Pizza 🍕 Building open source @ bit.dev