1

I found setting background color for entire <html> element (without height set to 100%) result in the whole viewport was set to that color

This html

<!DOCTYPE html>
<html>

<head>
  <style>
  html {
    background-color: green;
    border: 5px dashed white;
    margin : 20px
  }

  body {
    background-color: wheat;
    border: 5px dashed red;
    margin : 20px

  }
  </style>
</head>

<body>  
    1
    <br>
    2
    <br>
    3 
</body>

</html>

will result like this

enter image description here

Obviously, the height of html element is less than the height of viewport, why the background color could extend to whole viewport?

Jcyrss
  • 1,513
  • 3
  • 19
  • 31

2 Answers2

3

Because the spec says so:

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I tried `html{margin:20px; border:1px solid #000;} body{margin:20px;background:yellow; border: 1px solid #000;}` Spill happened and html, viewport all just got painted by yellow. Is this the intended behavior? There should be gap in backgrounds of `viewport` and `html` area - they should be white? Don't you think? – Deadpool Feb 12 '22 at 07:31
  • @Deadpool — Now you're asking about what happens when you set the background on the body element, which is a different question. Look at the paragraph I quoted from the spec. Then read the next paragraph. – Quentin Feb 12 '22 at 07:37
  • I know what happens, spill will happen. The question is on implementation in browser. I find this wrong and inconsistant. What do you think? – Deadpool Feb 12 '22 at 07:47
  • @Deadpool — I think you should read the part of the specification I pointed you at in my previous comment which explicitly says that is the correct behaviour. – Quentin Feb 12 '22 at 07:49
0

I guess that's just the browser trying to match colours with the HTMLs background to better blend in. I think it might look weird especially back in the days where most stuff was sized via pixel values.

Extending a browser page wouldn't result in a rough cut of colour where it changes to white or something. But I would guess that's a browserspecific implementation but don't quote me on that.