What is the universal selector in CSS?

The universal selector in CSS is denoted by the asterisk symbol (*) and is used to select all elements on a web page. This selector can be used to apply styles universally to every element within the scope of its placement.

Here's how the universal selector looks in a stylesheet:

* {
  /* CSS properties here will apply to all elements */
  margin: 0;
  padding: 0;
}

In the above example, the universal selector is used to remove the default margin and padding from all elements, which is a common practice in CSS resets to ensure a consistent starting point across different browsers.

The universal selector can be combined with other selectors to target specific scenarios. For instance:

  • To apply a style to all elements within a particular element:
#container * {
  /* Styles will apply to all elements within the element with the ID 'container' */
  color: blue;
}
  • To target all elements directly within a specific element (using the > child combinator):
#container > * {
  /* Styles will apply only to direct child elements of the element with the ID 'container' */
  font-weight: bold;
}

The universal selector is powerful but should be used judiciously, as it can have a significant impact on performance if applied carelessly, especially on large and complex web pages. It overrides the default styles of all elements, which can lead to unintended side effects if not managed properly. It's also important to note that specificity rules still apply; direct element selectors, class selectors, ID selectors, etc., will override the universal selector when styling a particular element.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon