iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

margin border padding content
Fig 1. From the inside out: content, padding, border, margin.

What each layer does

LayerPurposeSees backgrounds?
ContentThe text or image itself.Yes
PaddingSpace between content and border.Yes — uses the element's background.
BorderA line around the padding.Drawn on top of the background.
MarginSpace 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 &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Make width and height include the border and padding.

* { box-sizing: ; }

Test yourself

Q1. From inside out, the box model layers are…
Q2. Does an element's background show in the padding area?
Q3. What does `box-sizing: border-box` change?

Discussion

Loading…