CSS Box Model
Every element in CSS is a rectangle. The box model describes the four layers that make up that rectangle: content, padding, border, and margin.
The four layers
What each layer does
| Layer | Purpose | Sees backgrounds? |
|---|---|---|
| Content | The text or image itself. | Yes |
| Padding | Space between content and border. | Yes — uses the element's background. |
| Border | A line around the padding. | Drawn on top of the background. |
| Margin | Space between this box and other boxes. | No — always transparent. |
box-sizing
By default, width and height measure only the content layer — padding and border add on top. Most modern stylesheets flip that with:
Reset
* { box-sizing: border-box; }
Now width: 200px means the whole border-edge is 200px — much easier to reason about for layout.
Note: Vertical margins between block elements collapse: two stacked elements with
margin: 20px end up 20px apart, not 40px.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Box Model</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Make width and height include the border and padding.
* { box-sizing:
; }
It is the opposite of `content-box`.
Discussion
Loading…