Where to set font-family: body or html element?

The short answer is, you can use either. Since every displayed element is a descendant of the body element, and the body element itself is the child of the html element, all elements that inherit the font-family property will happily adopt it from either. (If a particular element doesn’t inherit it, you can always override its font-family property with a value of inherit.)

But what is best practice, and why? That’s a bit harder to answer, but I’ll have a go. Let’s start with semantics…

The html element represents the whole document (including non-visible metadata), while the body element represents the content of the document. Since font-family is a property of styled content, it would seem logical to apply it to body. That’s one point for body.

Next question: Where do the browsers define text formatting properties like font-family? I looked at the user agent stylesheets for Safari (WebKit), Mozilla Firefox and Chrome, and also used the Web Inspector on a page with no overriding CSS, but I couldn’t find a global font-family declaration anywhere. But here’s something interesting… In Safari, the global text color property is defined on the html element. So, if that’s anything to go by, it suggests WebKit browsers do define global font properties on the html element.

There are CSS resets that also tackle it here, like Bootstrap’s _reboot.scss file:

// 2. Change the default font family in all browsers.
html {
   font-family: sans-serif; // 2
   …
}

Still, we can override this on the body element, and that is just what Bootstrap does a few lines later:

body {
   margin: 0; // 1
   font-family: $font-family-base;
   …
}

Half a point to html?

The CSS specs (as far as I know) don’t dictate where font-family is declared (it applies to ‘all elements’), but it does give us some hints. The first code example in the W3C document CSS Fonts Module Level 3 is this:

body {
   font-family: Helvetica;
   font-weight: bold;
}

Another one is here:

body {
   font-family: "Gill Sans", sans-serif;
   font-size: 12pt;
   margin: 3em;
}

It explains:

The first declaration on the BODY element sets the font family to “Gill Sans”. If that font is not available, the user agent (often referred to as a “browser”) will use the sans-serif font family which is one of five generic font families which all users agents know. Child elements of BODY will inherit the value of the font-family property.

Another point to body.

Final scores:

body: 2
html: 0.5

Winner: body! 😀

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)