DEV Community

Youn
Youn

Posted on

CSS * Selector – Selects All Elements

πŸ˜„ 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;
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

References

CSS * Selector – Selects All Elements - codingCourses

The * selector (asterisk, also known as the universal selector) selects all elements in the document.

favicon coding.courses

Top comments (0)