Search code examples
htmlcssimagealignmentdocument-body

Why is the body background image not contained inside the body when the html tag has no background color set?


Google's 404 page uses margins and padding to center the content inside the body tag like this:

body {
    margin: 7% auto 0;
    max-width: 390px;
    min-height: 180px;
    padding: 30px 0 15px;
}

The image of the broken robot is then set as a background image on the body tag and positioned to the top right so that it appears just to the right of the main content.

* > body {
    background: url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;
    padding-right: 205px;
}

The html styles look like this:

html {
    background: #fff;
    color: #222;
    padding: 15px;
}

Why does the image appear in the top right hand corner of the page when the background color of the html tag is removed?

html {
    //background: #fff;
    color: #222;
    padding: 15px;
}

Broken plunkr example


Solution

  • The technical reason is "because the specification says so":

    For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element. Such backgrounds must also be anchored at the same point as they would be if they were painted only for the root element.

    This is likely because in the bad old days, the background of the page was determined by the bgcolor and background attributes on the body element, so CSS was made "compatible" with existing practises.