How spacing works on the web: CSS Box Model

The CSS Box Model consists of four areas: content, padding, border, and margin. Knowing how they work together in web development and design is essential.

Have you ever been confused about the spacing between elements on a webpage? Why are some boxes closer together and some farther apart?

Simply put, web browsers represent each element on a webpage as a rectangular box. This concept is known as the CSS Box Model.

Watch the lesson

CSS Box Model

The CSS Box Model defines the position and dimensions of HTML elements on a web page and consists of four main parts:

  • content (what's inside)

  • padding (space around contents)

  • border (line around contents)

  • margin (space outside borders)

 The image below demonstrates the model:

CSS Box Model

Below we'll cover each model section and explain how it works.

Content area

The content area is where the content for an element lives. It can be text, images, video, or anything else you want to display on your website.

If the content area is a block element, the following CSS properties can define the dimensions: widthmin-widthmax-widthheightmin-height, and max-height.

Padding

Padding is the space between an element's border and its content. The following properties can define the padding size: padding-toppadding-bottompadding-leftpadding-right, or the shorthand property padding.

Border

The border is the visible frame around your rectangle. These CSS properties set the border width, style, and color for all four sides: border-widthborder-style, and border-color, or the shorthand property border.

You can set each side of the border to different widths, styles, and colors with more granular CSS border properties.

When adding borders to an element, the border's size adds to the width and height of the box. For example, if a content area has a width of 100 pixels and a border of 2 pixels is added on each side, the content area will now have a width of 104 pixels.

Margin

Margin is the outermost area of the model and clears space outside the border. The following properties can define the margin size: margin-topmargin-bottommargin-leftmargin-right, or the shorthand property margin.

Margins have a weird characteristic known as margin collapse, which can transfer the margin to the parent element. In a case like this, you would use padding to increase the space between the child and the parent element.

Conclusion

The CSS Box Model consists of four areas: content, padding, border, and margin. Each has its function, and knowing how they work together in a design is essential. By understanding how they fit together and their function in the page layout, we can craft more well-developed websites.