π This post is based on the content from coding.courses.
Definition and Usage
The * selector (asterisk, also known as the universal selector) selects all elements in the document.
Basic Example
* {
color: #222222;
}
Note
The * selector applies to actual elements in the document, and pseudo-elements generated by CSS (such as ::before and ::after) are not included. This is because pseudo-elements are not actual elements in the document.
Using with Other Selectors
---- CSS ----
section * { /* Select all descendant elements of the section element */
background-color: gold;
}
---- HTML ----
<section>
<h3>Section title</h3>
<p>Section content</p>
</section>
In the example above, section * selects all elements inside the <section> element. The * selector can be used in combination with other selectors.
Common Use Cases of the * Selector
The * selector, which selects all elements in HTML, is commonly used to remove user agent stylesβthe default styles built into the browserβbefore any custom CSS is applied.
For example, elements such as <h1>~<h6> and <p> have margin-top and margin-bottom applied as default styles by the browser, even without custom CSS. The * selector is commonly used to reset these built-in browser styles.
If you do not reset these default browser styles, unexpected styling may occur because you might not account for the browser's default settings when styling the actual web page. This can make CSS styling highly inconvenient.
The following CSS example shows how to reset the default margin and padding from all elements and then apply custom styles to specific elements.
/* Reset default styles built into the browser */
* {
padding: 0;
margin: 0;
}
/* Apply custom styles */
p {
margin-top: 0.5em;
margin-bottom: 1em;
}
button {
padding: 0.5em 1.5em;
}
Top comments (0)