Percentage padding is not adding up total height correctly

So I have a page with html, header, body, div tags etc. For the CSS, I have:

* {
  margin: 0;
  padding: 0;
}
html {
  width: 100%;
  height: 100%;
}
body {
  width: 98%;
  height: 98%;
  padding: 1%;
}

My issue is there’s a scrollbar on the right side of the browser. Meaning the height is too high?

The html is set to 100% height and width. The body has a 1% padding which adds 1% top, right, bottom and left, so that’s width - 2 = 98 and height - 2 = 98.

So padding 1% height 98%, and width 98%. How am I getting a scrollbar?


solution

It’s not working as expected because the percentage-based padding is relative to the width of the element. If you resize the browser so that the height is greater than the width, you will notice that the scrollbar goes away (which is because the padding is relative to the width).

According to the spec:

8 Box model - 8.4 Padding properties:

The percentage is calculated with respect to the width of the generated box’s containing block, even for ‘padding-top’ and ‘padding-bottom’. If the containing block’s width depends on this element, then the resulting layout is undefined in CSS 2.1.

One possible work-around is to use viewport-percentage units such as vw in order to make the percentage relative to the width:

body {
  width: 98%;
  height: 98%;
  padding: 1vh 1vw;
}

You could also add box-sizing: border-box to include the padding in the element’s dimensions:

body {
  width: 100%;
  height: 100%;
  padding: 1%;
  box-sizing: border-box;
}