htmlcsscss-specificity

Why BODY tag doesn't override HTML tag properties?


I have applied this css to my html document:

html {
  background-color: red;
}

body {
  background-color: yellow;
}

and the background of the page gets red instead of yellow. body comes after html so it must override the red color of html. Why doesn't it happen? thanks in advance.


Solution

  • The HTML and BODY elements are different elements, so the cascade rules (including the order you placed your rulesets in) are not relevant here.

    Your source of confusion probably steps from the fact that CSS has some special rules for the HTML and BODY elements:

    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.

    So if you set just one of them, then that is the colour you will get.

    Here you have a red HTML element.

    html { background: red; }

    Here you have a yellow HTML element because it pulled the colour from the BODY element.

    body { background: yellow; }

    However, since you have set both those special rules don't apply.

    The HTML element is set to red and the BODY element is set to yellow.

    You just can't see it because your body element has no content so gets a computed height of zero.

    html { background: red; }
    body { background: yellow; }
    <p>Hello, world.
    <p>Since there is content in the body, it no longer has a zero height, so you can see its background.