0

I'm getting strange behaviour from margins. A vertical scrollbar appears even though I'm no where near the bottom. I assume this is the desired behaviour, considering that I tested this and got the same results in the latest versions of Chrome, IE11 and Firefox.

The following code results in a scrollbar

<html>
<head>
<style>
body { 
    margin: 0;
    height: 100%;
    padding: 1px;
}

div {
    margin: 15px;
}    
</style>
</head>
<body>
<div>Hmm</div>
</body>
</html>

Changing the body's padding to 0.1px results in no margin. Changing the body's padding to 0px also results in a margin. Also, adding box-sizing: border-box to the body removes the scrollbar as long as the padding is not zero.

I haven't added a Fiddle because I can't replicate it there. You need to test this in a simple html file.

Is this actually the expected behaviour? Is there a logical explanation why they implemented it like this?

r.h
  • 27
  • 2
  • 5

2 Answers2

3

Looks like the reason you're seeing the scrollbar is a combination of defining a height and setting a padding value. The height property dictates the height of an element's content, excluding the margin and padding added onto that value. The scrollbar appears after adding padding because you've set the content of the element's height to 100% of the page, plus the padding, causing the element's entire height to overflow.

Additionally, applying box-sizing to an element makes the height and width properties include padding in the value. Funny thing is, it doesn't include margin. So if you were to apply:

body {
  box-sizing: border-box,
  margin: 1px,
  padding: 0
}

You'd still see the scrollbar. Once understanding that an element's height property, by default, only dictates the height of the content within the element, it makes a little more sense.

Hope this helps :)

Jonathan Michalik
  • 1,492
  • 14
  • 15
0

Setting the height of the body to 100% makes it take all of the height of it's parent element which is the html element. The html element's width and height in turn are governed by the window it is in. Adding a margin or a border would increase the dimensions beyond the available space thus inducing the scroll. However, the other issue is that adding the margin to the div is pushing the body down by 15px. This has to do with collapsing margins. Check out https://stackoverflow.com/a/2680515/6184852 for further information.

Community
  • 1
  • 1
Doctor Strange
  • 351
  • 2
  • 7