0

By default body has an 8px margin. If I set a background color declaration for body, the entire page is filled with that color. Since margin is outside of the element, I expected that there would be a band of white around the outside. I thought maybe the margin was being added off screen but with Chrome dev tools I can see the margin is within the boundaries of the page. Why does the body margin work this way?

body {
  background-color: #ccc;
}
nCardot
  • 5,992
  • 6
  • 47
  • 83

2 Answers2

2

If html doesn't have a background color, it takes the same as the body. If you want a margin around the body, simply add

html {
    background: white;
}
SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
1

Your browser takes the internal root color:

Use padding instead:

The first color it can find is #ccc from body so html takes it.

body {
  background-color: #ccc;
}

You need a separate color style for html which is different from body:

html {
    background: white;
}

body {
  margin: 8px;
  background-color: #ccc;
}
enter image description here

However, because there is no content in body, so no height. We need to set height for both html and body to take 100% of your browser.

html {
    background: white;
}

body {
  margin: 8px;
  background-color: #ccc;
}

html,body{
  height:100%
}
Ray
  • 1,539
  • 1
  • 14
  • 27
  • *Your browser takes the internal root color:* this has nothing to do with backgrond. As you can see it's about *color* not *background-color* – Temani Afif Jan 15 '20 at 10:16