When it comes to deciding whether to apply the font-family
property to the html
or body
element, you have options. Both elements are connected in the document hierarchy, with all displayed elements being descendants of the body
element, which is itself a child of the html
element. This means that all elements can inherit the font-family
property from either one. And if an element doesn't naturally inherit it, you can always override its font-family
property by setting it to inherit
.
But what is considered best practice and why? Let's explore this further...
The html
element represents the entire document, including metadata that isn't visible, while the body
element specifically represents the content of the document. Since the font-family
property is related to styling content, it might make sense to assign it to the body
element. So, one could argue in favor of applying it to the body
.
Where do browsers define text formatting properties like font-family
? Browsing through user agent stylesheets for Safari (WebKit), Mozilla Firefox, and Chrome didn't reveal a global font-family
declaration. However, in Safari, the global text color
property is set on the html
element, hinting that WebKit browsers may define global font properties there.
CSS resets, such as Bootstrap's _reboot.scss
, address this issue by setting the default font family on the html
element:
// Change the default font family in all browsers.
html {
font-family: sans-serif;
…
}
Despite this, Bootstrap also overrides it on the body
element in the stylesheet:
body {
margin: 0;
font-family: $font-family-base;
…
}
According to CSS specifications, font-family
can be applied to 'all elements' without dictating where it should be declared. Looking at examples from W3C documents like the CSS Fonts Module Level 3 and CSS2 provides insights into setting font-family
on the body
element.
In the end, based on various considerations and guidelines, the scales seem to tip slightly towards assigning the font-family
property to the body
element rather than the html
element.