How to Use Universal Selector in CSS: Syntax and Examples
The CSS universal selector is
* and it matches all elements on the page. Use it to apply styles globally, for example, * { margin: 0; } removes margin from every element.Syntax
The universal selector uses a single asterisk * to select all elements in the HTML document.
Example parts:
*: selects every element{ ... }: contains CSS properties to apply
css
* {
property: value;
}Example
This example shows how to remove default margin and padding from all elements to create a clean base for styling.
css
/* Remove margin and padding from all elements */ * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; background-color: #f0f0f0; padding: 1rem; } h1 { color: #333; } p { color: #666; }
Output
A page with no default spacing around elements, a gray background, a heading in dark gray, and paragraph text in lighter gray.
Common Pitfalls
Using the universal selector can slow down your page if overused because it applies styles to every element.
Also, it can override more specific styles unintentionally if not used carefully.
Example of a common mistake:
/* Wrong: This removes margin from all elements including those you want spaced */
* {
margin: 0;
}
/* Better: Use universal selector only for box-sizing or reset, not all spacing */
* {
box-sizing: border-box;
}Quick Reference
- * selects all elements
- Use for resets like margin, padding, or box-sizing
- Be careful: can affect performance and override specific styles
- Combine with other selectors for more control (e.g.,
*:hover)
Key Takeaways
The universal selector (*) targets every element on the page.
Use it mainly for CSS resets like removing margin and padding.
Avoid overusing it to prevent performance issues and unwanted style overrides.
Combine with other selectors for more specific styling.
Always test your styles to ensure the universal selector does not break your layout.