Cooperweb.dev

The CSS Box Model

headshot of Lee Cooper
Lee Cooper
The CSS Box Model
The CSS Box Model

Everything is a Box

Each HTML element on a web page is represented as a box, known as the CSS Box Model, and is made up of four areas that define how elements are presented on the screen.

These areas are: Content, Padding, Border, and Margin.

Picture frames are one way to illustrate the CSS Box Model. Each of the box model areas correlate to an area in this picture of the Shiba Inu.

Picture frame with a photo of a Shiba Inu
Picture frame with a photo of a Shiba Inu

Content

This is the actual thing represented in the box on the web page, such as a paragraph of text or an image. It's the cute dog in the photo frame.

Padding

The area or space between the content and the border. It separates the dog picture from the border of the picture frame.

Border

The edge of the content and its padding. It's the physical frame in the picture that contains both the Shibu Inu and the space around it.

Margin

The space beyond the border. Used to provide spacing between one HTML Element, and another. Adding to the analogy, this would be the space between one picture frame and others around it.

In the Browser

In practice, a HTML Element can be inspected to see each area's value by using the browser dev tools.

Photo of a Shibu Inu used to illustrate CSS Box Model concepts Photo of box model in browser dev tools

Right clicking the Shibu Inu image and selecting inspect will launch the browser dev tools with the elements tab selected. On the right side is a styles tab, and scrolling to the bottom reveals an interactive display that lists the calculated values for content, padding, border, and margin dimensions.

Since relative units like rem and em are often used for sizing (rather than static pixel sizes), this provides a convenient way to inspect an element's dimensions in different states, such as on a desktop screen or a mobile phone display.

In Conclusion

The CSS Box Model is a key introductory concept to the world of CSS. Once it is understood that everything on a web page is made up of boxes, it becomes easier to view how each element is sized and its behavior around other elements.

Challenge:

Using the inspect tool, explore this page and find an example implementation of each of the four CSS Box Model areas. How do they interact? Does every element have a value for each of the four areas? Does specifying the value for one area (for example, margin) apply it to all sides of the element?