I have a div with no content as a lone child of the document body. width: 100%
and height: 100%
styles are applied to it. Applying any amount of padding (width or height) to the div causes it to grow in size, past the parent body.
The HTML Document:
<html>
<body>
<div></div>
</body>
</html>
CSS applied to the previous HTML Document:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
div {
width: 100%;
height: 100%;
padding: 2rem;
}
Can someone please explain this behavior and how to prevent it? I thought padding would shrink content until there is no space left before expanding width and height, but the div is without content and has ample room for extra padding.
2
Answers
try :
* { box-sizing: border-box; }
Normally with the CSS box model, padding, border, and margin do not affect the width or height of an element.
In the below image you can see the box model of the
div
with padding. The width and height (blue box in the middle) are equal to the window width and height, regardless of the padding, which adds an extra 32px on all sides to that, causing overflow. (Image taken from Chrome DevTools)To change this behaviour, you can use the
box-sizing
property:Now, the dimensions of the div now take padding into account. The blue box in the middle has been shrunk to fit the padding into the set dimensions.
Some people recommend to set this property on every element ({ box-sizing: border-box } FTW)