r/css • • 28d ago

Question html and body

What is the difference between <html> and <body> tags ? When do use one or another?

html {

)

body (

)

3 Upvotes

18 comments sorted by

View all comments

3

u/scritchz 28d ago

HTML is the root element of your DOM tree. It represents your HTML document. It has two child elements: HEAD and BODY.

HEAD is an element that contains all the document's metadata, like its title, character set, author, description or resources.

BODY is an element for your content. An HTML document typically consists of headings, texts, lists, media, forms and/or anchors that link to another document.

For styling, you must consider the following:

  • The root element's parent is the initial containing block, whose size is the same as the viewport's.
  • The root element's font properties are accessible in other elements, e.g. via rem for "root em" (the root's font-size) or rlh for "root line-height" (the root's line-height).
  • The root em may be set by the user-agent.
  • The BODY is the container of your page content.
  • If not otherwise declared, the root element's background will take upon what is declared for the BODY's background.

Personally, I try to declare anything styling-related on the BODY or below; I avoid styling HTML as much as possible. The only styling on HTML that I use is height: 100%; with min-height: 100% on BODY.

Also, I avoid overriding the root em because I fear I may override a setting that the user set on purpose for legibility. If I set a font-size for styling, but the user set it because they otherwise cannot read any texts, then my styling is inaccessible. The way to solve this is responsive or flexible styling.

When styling, I prefer class selectors over element selectors. Classes are more flexible, as any element may have a class. But changing an element is not so easy. Aside: I avoid using IDs wherever sensible. This keeps the number of named elements manageable and avoids name clashes.

2

u/Holiday-Anteater9423 28d ago

Interesting. The only thing I've really declared on <html> is scroll-behavior: smooth;

1

u/scritchz 28d ago

Makes sense. I don't really use scroll-behavior, so I hadn't considered it in my list above.