Reputation: 209
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?
Upvotes: 6
Views: 1621
Reputation: 78676
In CSS, percentage margin and padding is relative to the width of the container, as Josh Crozier has already explained that in his answer.
I suggest to set the percentage padding on the <html>
element, the root of the document, plus box-sizing: border-box;
together it gives you the equal space around.
border-box
Length and percentages values for width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified width and height properties. -W3C
html {
background: silver;
box-sizing: border-box;
height: 100%;
padding: 5%;
}
body {
background: pink;
height: 100%;
margin: 0;
}
Upvotes: 3
Reputation: 240868
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;
}
Upvotes: 12