Giving background-color to body applying whole page. Why?

后端 未结 6 2013
梦谈多话
梦谈多话 2021-01-05 00:10



        
6条回答
  •  不知归路
    2021-01-05 01:01

    The main reason is because the HTML takes the background-color of BODY since:

    The background of the root element becomes the background of the canvas and covers the entire canvas [...]

    So since the default background-color of HTML is transparent it will take the one from BODY. However applying a color to both the HTML and BODY elements you will see that the BODY background doesn't cover the whole page anymore.

    html {
      background-color: blue;
    }
    
    body {
      background-color: red;
    }
    
    
    
      
    Hello World!

    The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for background-position) at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

    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.

    From W3 - 14 Colors and Backgrounds.

提交回复
热议问题