The universal selector in CSS is denoted by an asterisk (*
) and is used to select all elements within a document. This selector is powerful because it applies styles to every element in the HTML, making it useful for applying global styles such as resetting margins and padding or setting a default box-sizing for all elements.
/* Apply a global reset to all elements */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Other styles */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: blue;
text-align: center;
margin-top: 20px;
}
p {
font-size: 16px;
color: green;
padding: 10px;
}
button {
background-color: yellow;
border: 2px solid black;
padding: 10px 20px;
cursor: pointer;
margin: 10px 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Universal Selector Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with universal selector applied.</p>
<button>Click Me!</button>
</body>
</html>
Universal Selector (*
):
margin: 0;
: Removes the default margin from all elements.padding: 0;
: Removes the default padding from all elements.box-sizing: border-box;
: Ensures that the width
and height
properties include the content, padding, and border of the element, making sizing more predictable.Other CSS Rules:
body
, h1
, p
, and button
elements after the global styles set by the universal selector.box-sizing: border-box
that should apply to all elements.* + * { margin-top: 1em; }
, which applies a margin only to elements that follow another element.