Every element you see on a web page is made up of one or more rectangular boxes. The CSS box model explains how these boxes are arranged. Each box can have different features, but they all include a content area and can have optional padding, border, and margin areas.
The diagram below shows how properties like width, height, padding, border, and margin influence the space an element occupies on a web page.
Padding refers to the clear space between an element's content and its border (or the edge of the box if there's no border), while margin is the clear space surrounding the border.
If an element has a background color, it will show through its padding area. The margin area always remains transparent, allowing the background color of the parent element to show through.
When you set the width and height of an element using CSS properties like width
and height
, you're actually setting the dimensions of the content area. The actual size of the element's box depends on various factors.
Here's how the total space an element's box occupies on a web page is calculated:
Box Size | CSS Properties |
---|---|
Total Width | width + padding-left + padding-right + border-left + border-right + margin-left + margin-right |
Total Height | height + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom |
We'll delve into each of these CSS properties in upcoming chapters.
Now, let's explore an example to see the box model in action:
div {
width: 300px;
height: 200px;
padding: 15px; /* padding set for all four sides */
border: 10px solid black; /* border set for all four sides */
margin: 20px auto; /* top and bottom margin set to 20 pixels, left and right margin set to auto */
}
Note: In the CSS box model, the content area of an element's box is where its content—like text, images, or videos—appears. It may also contain boxes of descendant elements.