4

I can set global CSS properties in one of the following blocks:

* {

}

html {

}

body {

}

What is the difference between them? How does each setting affect the page style?

When I set font-family or color, where do I have to place it?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Michael
  • 32,527
  • 49
  • 210
  • 370
  • there is a huge difference between * and body – CRABOLO Jan 17 '14 at 01:03
  • @AlienArrays Could you explain it? – Michael Jan 17 '14 at 01:04
  • 2
    * selects all elements. Including but not limited to `

    – CRABOLO Jan 17 '14 at 01:06
  • Typically you will want to avoid styling these broad nodes but rather include a proven CSS reset that will leverage them to level out the various browser quirks. That said, it's always useful to add classes to these nodes so that you can scope certain circumstances easily. For instance, you could add the class .ie7 to the html node using an html conditional comment and then to add IE7 specific CSS to your site you could just scope a selector with .ie7. Your base fonts should start with body and then go to headings and so on. – Smith Jan 17 '14 at 02:10
  • 3
    Related questions: [Should global css styles be set on the html element or the body element?](http://stackoverflow.com/questions/4565942/should-global-css-styles-be-set-on-the-html-element-or-the-body-element) and [What's the difference in applying CSS to html, body, and *?](http://stackoverflow.com/questions/7187569/whats-the-difference-in-applying-css-to-html-body-and) (not sure if the second one is a duplicate because the properties being set are different) – BoltClock Jan 17 '14 at 02:16

1 Answers1

14

* will select all elements.

html will select the <html> element.

body will select the <body> element.

The reason that sometimes they do the same thing is inheritance, meaning that child elements of the element you apply the style too will get that same style. (See the "Inherited?" column of the spec for which properties do this).

If inheritance applies, you should select body or html because * is generally slower, tho it won't make much of a difference on modern browsers.

Also, don't overuse any of these. They are very broad, and you don't want to go undoing your styles for specific elements. h1.header {color: red;} is better than

* {
    color: red;
}
h2, h3, p, ul, ol {
    color: black;
}

or

* {
    color: red;
}
:not(h1) {
    color: black;
}
h1.other-header {
    color: black;
}
bjb568
  • 11,089
  • 11
  • 50
  • 71
  • When I set font-family or color where do I have to place it in? – Michael Jan 17 '14 at 01:04
  • 1
    @confile I would recommend `body` because `color` and `font-family` inherits. Please don't overuse *, tho, it's slow, and in many cases you want to cover almost everything, not everything. Undoing styles is evil. – bjb568 Jan 17 '14 at 18:45