Sometimes I see people apply global css styles to html, sometimes I see them apply them to body, with both raw css and javascript.
Are there any differences between the two? Which is the standard to make a global css style? Is there anything I should know when picking between them?
I’m assuming that “global page styling” here refers to things such as fonts, colors and backgrounds.
Personally, I apply global page styling, for the most part, to
bodyand the simple element selectors (p,h1, h2, h3...,input,img, etc). These elements are more closely related to the presentation of content of an HTML page to the user.My rationale for this is simple: the presentational attributes
bgcolor,background,text,topmargin,leftmarginand others were given to thebodyelement, not thehtmlelement. These attributes are now converted to their respective CSS rules with extremely low precedence in the cascade:Most if not all implementations I’m aware of will convert these to CSS rules on
body, based on their HTML equivalents. Others such aslink,alinkandvlinkwill becomea:link,a:activeanda:visitedrules respectively.Of course, it should be noted that CSS itself doesn’t really have any semantics to it per se, as it’s a styling language in itself which is completely separate from the content structure of an HTML document. Although the introduction to CSS2.1 covers the basics of styling an HTML document, note that the section calls itself non-normative (or informative); this means it doesn’t set any hard and fast rules for CSS implementers to follow. Instead, it simply provides information for readers.
That said, certain styles may be applied to
htmlto modify viewport behavior. For example, to hide the page scrollbars use:You can also apply rules to both
htmlandbodyfor interesting effects; see the following questions for details and examples:Note that
htmlis not the viewport; the viewport establishes an initial containing block in whichhtmlis situated. That initial containing block cannot be targeted with CSS, because in HTML, the root element ishtml.Note also that, technically, there is no difference between applying properties to
htmlandbodythat are inherited by default, such asfont-familyandcolor.Last but not least, here is an excellent article that details the differences between
htmlandbodyin terms of CSS. In summary (quoted from its first section):As the root element,
htmlis more closely associated with the browser viewport thanbody(which is why it sayshtmlhasoverflow: autofor scrollbars). Note however that the scrollbars are not necessarily generated by thehtmlelement itself. By default, it’s the viewport that generates these scrollbars; the values ofoverfloware simply transferred (or propagated) betweenbody,html, and the viewport, depending on which values you set. The details of all this are covered in the CSS2.1 spec, which says:The last bullet point probably has its roots in the aforementioned
topmarginandleftmarginattributes of thebodyelement.