Should global css styles be set on the html element or the body element?
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 body
and 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
, leftmargin
and others were given to the body
element, not the html
element. These attributes are now converted to their respective CSS rules with extremely low precedence in the cascade:
The UA may choose to honor presentational attributes in an HTML source document. If so, these attributes are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet.
Most if not all implementations I'm aware of will convert these to CSS rules on body
, based on their HTML equivalents. Others such as link
, alink
and vlink
will become a:link
, a:active
and a:visited
rules 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 html
to modify viewport behavior. For example, to hide the page scrollbars use:
html {
overflow: hidden;
}
You can also apply rules to both html
and body
for interesting effects; see the following questions for details and examples:
- What's the difference in applying CSS to html, body, and *?
- Applying a background to <html> and/or <body>
Note that html
is not the viewport; the viewport establishes an initial containing block in which html
is situated. That initial containing block cannot be targeted with CSS, because in HTML, the root element is html
.
Note also that, technically, there is no difference between applying properties to html
and body
that are inherited by default, such as font-family
and color
.
Last but not least, here is an excellent article that details the differences between html
and body
in terms of CSS. In summary (quoted from its first section):
- The
html
andbody
elements are distinct block-level entities, in a
parent/child relationship.- The
html
element's height and width are controlled by the browser window.- It is the
html
element which has (by default)overflow:auto
, causing
scrollbars to appear when needed.- The body element is (by default)
position:static
, which means that
positioned children of it are
positioned relative to thehtml
element's coordinate system.- In almost all modern browsers, the built-in offset from the edge of the
page is applied through amargin
on
thebody
element, notpadding
on the
html
element.
As the root element, html
is more closely associated with the browser viewport than body
(which is why it says html
has overflow: auto
for scrollbars). Note however that the scrollbars are not necessarily generated by the html
element itself. By default, it's the viewport that generates these scrollbars; the values of overflow
are simply transferred (or propagated) between body
, html
, and the viewport, depending on which values you set. The details of all this are covered in the CSS2.1 spec, which says:
UAs must apply the 'overflow' property set on the root element to the viewport. When the root element is an HTML "HTML" element or an XHTML "html" element, and that element has an HTML "BODY" element or an XHTML "body" element as a child, user agents must instead apply the 'overflow' property from the first such child element to the viewport, if the value on the root element is 'visible'. The 'visible' value when used for the viewport must be interpreted as 'auto'. The element from which the value is propagated must have a used value for 'overflow' of 'visible'.
The last bullet point probably has its roots in the aforementioned topmargin
and leftmargin
attributes of the body
element.
What is the difference between html, body and * when setting global CSS Properties
*
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;
}
CSS - Styling body element vs. styling html element
Here are two articles about this very thing:
How to center and layout pages without a wrapper
Styling HTML and body elements
Should we be applying CSS to body vs. html elements?
I believe that the W3C recommends that you apply any page-wide styles to the <body>
element.
What is the difference between applying css rules to html compared to body?
There is no real difference (if you're just talking about where to apply background
, otherwise BoltClock's answer to this other question is a better fit). html
is an element, just like body
is.
Both are valid choices, and both will both work in all common browsers.
The YUI Reset for instance, chooses to set a background
on the html
element instead of body
:
http://yui.yahooapis.com/3.3.0/build/cssreset/reset.css
This requires that you set your background
on html
, for instance see: can't change body background color using CSS reset
See: http://dev.w3.org/csswg/css3-background/#special-backgrounds
The background of the root element becomes the background of the
canvas and its background painting area extends to cover the entire
canvas, although any images are sized and positioned relative to the
root element as if they were painted for that element alone. (In other
words, the background positioning area is determined as for the root
element.) If the root's ‘background-color’ value is ‘transparent’, the
canvas's background color is UA dependent. The root element does not
paint this background again, i.e., the used value of its background is
transparent.
And:
For documents whose root element is an HTML HTML element [HTML401] or
an XHTML html element [XHTML11]: if the computed value of
‘background-image’ on the root element is ‘none’ and its
‘background-color’ is ‘transparent’, user agents must instead
propagate the computed values of the background properties from that
element's first HTML BODY or XHTML body child element. The used values
of that BODY element's background properties are their initial values,
and the propagated values are treated as if they were specified on the
root element. It is recommended that authors of HTML documents specify
the canvas background for the BODY element rather than the HTML
element.
What that wall of text is saying is demonstrated here:
background
on justbody
: http://jsfiddle.net/hhtzE/background
onhtml
andbody
: http://jsfiddle.net/hhtzE/1/background
onlyhtml
: http://jsfiddle.net/hhtzE/2/
Is it necessary (or advisable) to add CSS styling to the HTML element?
Well the major reason i can think of is that, for specifying height
in %
the elements parent needs to have a height set explicitly.
Assume you've a container <div>
which you need to be of 100%
height and responsive. simply applying height:100%
won't work unless you specify a height for it's parent <body>
.
Hence we'll apply height:100%
for the <body>
- Now, this won't work since <body>
's parent doesn't have a height set explicitly - which is our <html>
element.
Hence we apply
html{
height:100%;
}
...!
This is not required if your design is not responsive , i.e if you're setting fixed dimensions in pixels
styled-components - how to set styles on html or body tag?
You can, of course, maintain a separate CSS file that you include in your HTML via a <link>
tag.
For v4
:
Use createGlobalStyle from Styled-components.
import { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle`
body {
color: ${props => (props.whiteColor ? 'white' : 'black')};
}
`
<React.Fragment>
<GlobalStyle whiteColor />
<Navigation /> {/* example of other top-level stuff */}
</React.Fragment>
Pre v4
:
Styled-components also exports an injectGlobal
helper to inject global CSS from JavaScript:
import { injectGlobal } from 'styled-components';
injectGlobal`
html {
height: 100%;
width: 100%;
}
`
See the API documentation for more information!
How to style body element in MUI
Material-UI v5
You can change the body styles by overriding MuiCssBaseline
styles in createTheme()
:
import CssBaseline from "@mui/material/CssBaseline";
import darkScrollbar from "@mui/material/darkScrollbar";
import { createTheme, ThemeProvider } from "@mui/material/styles";
const theme = createTheme({
components: {
MuiCssBaseline: {
styleOverrides: {
body: {
...darkScrollbar(),
color: "darkred",
backgroundColor: "grey",
"& h1": {
color: "black"
}
}
}
}
}
});
export default function GlobalCssOverride() {
return (
<ThemeProvider theme={theme}>
<CssBaseline />
<Content />
</ThemeProvider>
);
}
Material-UI v4
You can apply the styles to the body
using @global class
like this:
const useGlobalStyles = makeStyles({
"@global": {
body: {
backgroundColor: "tomato"
}
}
});
const theme = createMuiTheme({});
function MyThemeProvider({ children }) {
useGlobalStyles();
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
function App() {
return (
<MyThemeProvider>
<Button variant="contained" color="primary">
Button
</Button>
</MyThemeProvider>
);
}
If you create the project by create-react-app
, you can also use css/scss module to style any element globally:
/* styles.css */
body {
color: white;
font-size: 15px;
}
import React from "react";
import Button from "@material-ui/core/Button";
import "./styles.css";
function App() {
return (
<Button variant="contained" color="primary">
Hello World
</Button>
);
}
Live Demo
How can I add style to the body element with JSS?
You can use the syntax introduced by jss-plugin-global
'@global': {
body: {...}
}
Also recommend creating a separate component for this and wrap your component with it. Otherwise your specific component becomes less reusable.
Related Topics
How to Stream Audio/Video Files Such as Mp3, Mp4, Avi, etc Using a Servlet
What Does It Mean in HTML 5 When an Attribute Is a Boolean Attribute
Apply Style to Parent If It Has Child With Css
How to Use Xpath Contains() For Specific Text
How to Draw a Trapezium/Trapezoid with CSS3
CSS Background Image Not Loading
Css3 Border-Radius Clipping Issues
How to Specify a Starting Number for an Ordered List
Setting the Cursor in the Element's Default Styles, or in Element:Hover
Firefox Linux (Centos) Responsive Design Image Scaling
Soft Hyphen in HTML (<Wbr> VS. &Shy;)
How to Disable Google Translate from HTML in Chrome
Media Queries For Different Zoom Levels of Browser
What Values Can Appear in the "Selected" Attribute of the "Option" Tag
How to Make ≪Div≫ Fill ≪Td≫ Height