Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Universal Selectors in CSS
The universal selector in CSS is represented by an asterisk (*) and matches every element in an HTML document. Unlike type selectors that target specific tags like h1 or p, the universal selector applies styles to all elements at once.
Type Selector vs Universal Selector
Type selectors target specific HTML elements:
h2 {
color: #FFFF00;
}
The universal selector targets all elements:
* {
color: #FFFF00;
}
Example: Universal Selector in Action
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p>This is a paragraph.</p>
<div>This is a div.</div>
</body>
</html>
Common Use Cases
The universal selector is commonly used for:
- CSS Reset: Removing default browser margins and padding
- Box-sizing: Setting consistent box model behavior
- Font inheritance: Applying a base font to all elements
Performance Consideration
While powerful, the universal selector can impact performance when used excessively, as it applies to every element. Use it strategically for global resets rather than frequent styling.
Example: CSS Reset with Universal Selector
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
}
h1 {
color: blue;
}
Conclusion
The universal selector (*) is a powerful CSS tool for applying styles to all elements. It's most commonly used for CSS resets and global styling, but should be used thoughtfully due to performance considerations.
