DEV Community 👩‍💻👨‍💻

Aditya Patnaik
Aditya Patnaik

Posted on

Why padding in a div affects other elements?

This problem is documented in the official MDN docs.

By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height, you have to adjust the value you give to allow for any border or padding that may be added - MDN

To handle this behavior, we make use of the box-sizing attribute and set it to border-box for all elements. Like so:

* {
  box-sizing: border-box;
}

border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements. - MDN

This makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble on while laying out your content.

The result of using the box-sizing: border-box; is so much better, many developers want all elements on their pages to work this way.

Many browsers already use box-sizing: border-box; for many form elements (but not all - which is why inputs and text areas look different at width: 100%

Top comments (0)

Find and follow new tags! 🤔 Did you know?   DEV has a variety of tags to help you find the content you like. Find and follow your favorite tags