Skip to main content

CSS Box Model

The CSS Box Model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:

Box-model

When you don’t want content to touch the edges of a container you'll usually want to use padding. margin is used when you want to push an element away from other elements. It's good practice to let the element you want to push, do the pushing.

Box-sizing

The CSS property box-sizing sets how the width and height of an element are decided. By default in the CSS box model, when an element has any border or padding, they are added on top of the width and height to arrive at the size of the box that's rendered on the screen. We can revert this effect by setting box-sizing: border-box. This makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble upon while laying out your content. To ease your styling experience, use the wildcard selector to have all elements start out with the border-box style:

* {
box-sizing: border-box;
}
info

When using position: relative or position: absolute, use of content-box allows the positioning values to be relative to the content, and independent of changes to border and padding sizes, which is sometimes desirable.

Further reading