skip to Main Content

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


  1. try :
    * { box-sizing: border-box; }

    Login or Signup to reply.
  2. 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)

    Box Model diagram showing the div with box-sizing: content-box

    To change this behaviour, you can use the box-sizing property:

    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    
    div {
        width: 100%;
        height: 100%;
        padding: 2rem;
        box-sizing: border-box;
    }
    <html>
      <body>
        <div></div>
      </body>
    </html>

    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.

    Box Model diagram showing the div with box-sizing: border-box

    Some people recommend to set this property on every element ({ box-sizing: border-box } FTW)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search