CSS – Universal ‘*’ Selector vs. HTML or Body Selector

coding-stylecssdesign-patternshtml

Applying styles to the body tag will be applied to the whole page, so

body { font-family: Verdana }

will be applied to the whole page. This could also be done with

* {font-family: Verdana} 

which would apply to all elements and so would seem to have the same effect.

I understand the principle that in the first instance the style is being applied to one tag, body for the whole page whereas in the second example the font is being applied against each individual html elements. What I am asking is what is the practical difference in doing that, what are the implications and what is a reason, situation or best practice that leads to using one over another.

One side-effect is certainly speed (+1 Rob). I am most interested in the actual reason to choose one over the other in terms of functionality.

Best Answer

Functional differences between these two choices of CSS selector...(my take)

body

  • Applies style properties to body element.
  • Elements within body may inherit the property values. Some properties default to 'inherit'.
  • Style declarations that match an element within body can override the inherited style.

The Universal Selector * (all elements)

  • Applies style properties to all individual elements.
  • Replaces inherited style properties, and default 'initial values'. Blocks inheritance.
  • Other, more specific css selectors that match an element will replace the style properties applied by *.

Suggestions

  1. Use body for style properties that default to inherit, such as font, color, in order to provide a sensible default value for elements, reducing the need to explicitly code for every case, and preserving the ability for elements contained at lower levels below body to inherit from their parents.
  2. Probably better not to use the Universal Selector * in this case. It interrupts inheritance between other elements within body, and may force you to write more css rules to compensate. It can be a factor in slowing rendering of pages. This depends on the size and content of the page and how many css rules there are.
Related Topic