Web Development

The CSS Box Model Explained With Real Examples

Flat illustration of nested boxes showing content, padding, border and margin

Every element on a web page is treated as a rectangular box. That box has four layers: the content in the middle, padding around the content, a border around the padding, and margin outside the border. If you understand those four layers, you can explain most spacing and sizing surprises in CSS. The content is the text, image or other material inside the element. Padding is the space between the content and the border, and it takes the background colour of the element. The border is a line around the padding and content. Margin is the space outside the border, and it stays transparent, so the page background shows through it.

This guide works through each layer with a card example you can reuse. You will see how width is calculated, why an element can end up wider than the width you set, and when to use margin instead of padding. The examples use plain CSS, and they build on the page structure covered in the guide to HTML basics for beginners. Once the box model is clear, layout tools such as Flexbox and Grid become easier to reason about, because those tools position boxes rather than changing what a box is.

The four layers in order

Start with a simple card. The card holds a heading and a paragraph, and the card itself is the element whose box you are shaping. The heading and paragraph are the content. If you add padding to the card, the heading and paragraph move away from the card edges, but they stay inside the card background. If you add a border, a line appears around the padded area. If you add a margin, the card moves away from the elements around it, without changing anything inside the card.

LayerWhere it sitsWhat it does
ContentCentre of the boxHolds the text, images or nested elements
PaddingBetween content and borderCreates space inside the element and shows its background
BorderBetween padding and marginDraws a line around the element, with a style, width and colour
MarginOutside the borderCreates space between this element and its neighbours

How width is calculated

Width calculation is where most confusion starts. Under the default setting, called content-box, the width property sets the width of the content area only. Padding and border are then added to that width. A box with a width of 300 pixels, padding of 20 pixels on each side, and a border of 2 pixels on each side does not occupy 300 pixels on the page. It occupies 344 pixels: 300 for the content, plus 40 for the two sides of padding, plus 4 for the two sides of the border. Margin is not part of that total, because margin is space outside the box, but it still affects where the box sits.

.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #18181B;
  margin: 16px;
}

The box-sizing property changes this calculation. When box-sizing is set to border-box, the width includes the content, the padding and the border together. The same card with a width of 300 pixels then occupies 300 pixels in total, and the content area shrinks to make room for the padding and border. Many developers set border-box on all elements at the start of a stylesheet, so that widths behave the way they expect when they add padding to a layout column. That choice is a convention, not a rule built into CSS, and it is worth stating in a project so that everyone working on the stylesheet uses the same model.

* {
  box-sizing: border-box;
}

.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #18181B;
}

Padding, border and margin in practice

Padding is the right tool when you want space inside a coloured or bordered area. A button with padding feels larger and easier to press, and the background colour fills the padded area, so the button still reads as one unit. A card with padding keeps its text away from its border, which makes the card easier to read. Without padding, text touches the border, and the result looks cramped even if the colours and fonts are fine.

Margin is the right tool when you want space between separate elements. Two cards stacked on a page need margin between them, because they are separate units and the space between them should not carry either card background. Margins on neighbouring block elements can collapse, which means the larger of two adjoining margins wins and the smaller one disappears into it. That behaviour surprises beginners, but it exists so that paragraphs and headings keep a consistent rhythm without doubling the space between them. If the gap between two elements is smaller than you set, margin collapsing is a likely cause, and the fix is usually to set margin on one side only, or to use a different layout method for that gap.

Common mistakes

The first mistake is setting a width in a percentage and then adding padding without changing box-sizing. A column set to 50 percent width with 20 pixels of padding on each side will overflow its row under content-box, because the total width is more than 50 percent. The row then wraps or overflows, and the cause is not obvious from the width alone. Switching that element to border-box, or moving the padding to an inner element, fixes the overflow without changing the intended column width.

The second mistake is using margin to create space inside a coloured area. Margin sits outside the border, so it does not carry the background colour, and the coloured area stays small while the gap grows. The result looks like the element is floating away from its own background. Padding is the fix in that case, because padding extends the background to cover the space. A related mistake is adding margin to every side of every element, which makes spacing hard to predict when margins collapse. Setting margin in one direction, usually below an element, keeps the rhythm simpler to follow.

The third mistake is treating inline elements as if they were boxes in the same way as block elements. A link inside a paragraph can take padding, and the horizontal padding will affect the line, but vertical padding and vertical margin behave differently on inline elements and can overlap neighbouring lines without pushing them apart. The guide to CSS Flexbox and Grid covers layout choices for larger structures, and for small inline pieces it is often better to change the display type or to accept that inline spacing has limits. Checking the display type of an element is a useful step whenever box behaviour looks wrong.

Where the box model does not solve the problem

The box model explains one element at a time, and it does not decide how several elements share a row or a page. That job belongs to layout methods such as Flexbox and Grid, which control alignment, wrapping and gaps between boxes. The gap property in those layouts creates space between items without the collapsing behaviour of margins, and it is often the cleaner choice for a row of cards or a grid of items. The box model still matters there, because each item in a flex or grid layout is still a box, but the spacing between items is handled by the layout method rather than by individual margins.

Worked example: sizing a card step by step

Take a card that should be 300 pixels wide on the page. With the default content-box sizing, setting width to 300 pixels sizes only the content area. Padding and border are added on top, so a card with 20 pixels of padding and a 2 pixel border ends up 344 pixels wide. That surprise is the source of many layout complaints, and it is why most stylesheets switch the whole page to border-box sizing, where width includes padding and border.

* {
  box-sizing: border-box;
}
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #333;
}

With border-box, the same card measures 300 pixels wide in total, and the content area shrinks to fit inside the padding and border. The layout becomes predictable, because the width you set is the width you see. Apply the border-box rule globally at the start of a stylesheet, so every element follows the same arithmetic and you never have to remember which elements use which model.

Margins behave differently from padding, because they sit outside the border and they can collapse with neighbouring margins. Two stacked blocks with a 20 pixel bottom margin on the first and a 30 pixel top margin on the second do not end up 50 pixels apart. The larger margin wins, and the gap is 30 pixels. That collapsing rule surprises beginners, but it exists so that paragraphs in an article keep even spacing without special handling for the first and last paragraph.

Padding, border and margin in a real layout

Padding is space inside an element, between its content and its border. It takes the background of the element with it, so a card with a coloured background shows that colour across its padding as well. Margin is space outside the element, between its border and its neighbours, and it stays transparent. Border sits between the two, and it can carry a colour, a width and a style of its own. Keeping those three roles separate makes layout decisions easier, because each question has a clear answer: space inside is padding, space outside is margin, and a visible edge is border.

A button shows the distinction well. Padding gives the label breathing room inside the button, so the text does not touch the edge. Margin separates the button from the next button, so the two do not run together. A border draws the button outline. If the button text touches the edge, the padding is too small. If two buttons touch each other, the margin is missing. Naming the problem in those terms points straight at the property to change.

Shorthand properties set several sides at once. One value sets all four sides, two values set vertical then horizontal, three values set top then horizontal then bottom, and four values run clockwise from the top. The four-value form is the easiest to remember once you learn the clockwise order, and it avoids the mistake of setting the sides in the wrong sequence. Write the longhand form when only one side needs a value, so the intent stays clear to the next reader.

When margins collapse and when they do not

Margin collapsing applies to vertical margins between block-level boxes in normal flow, and it follows a few rules that are worth learning once. Adjacent sibling margins collapse to the larger of the two. A parent and its first child can collapse when nothing separates them, such as padding or a border, which is why a child with a top margin can appear to push the whole parent down instead of moving inside it. Empty blocks with no content and no padding can collapse their own top and bottom margins into one.

Several situations stop collapsing. Flex and grid items do not collapse their margins with each other, which is one reason a flex row behaves more predictably than a stack of plain blocks. Padding or a border between a parent and a child also stops the collapse, as does making the parent establish a new formatting context, for example with overflow set to auto. Knowing these exceptions matters, because the fix for a collapsing margin is often to add a small amount of padding to the parent rather than to keep increasing the child margin and wondering why nothing changes.

SituationMargins collapse?
Two stacked paragraphsYes, to the larger margin.
Two flex items in a rowNo, flex items keep their own margins.
Parent and first child, no padding betweenYes, unless separated by padding or a border.
Parent with padding, child with marginNo, the padding separates them.

When a gap looks wrong, open the developer tools box model diagram for the element. It shows content, padding, border and margin as nested boxes with their sizes, so you can see which part is actually producing the gap instead of guessing from the rendered page.

Debugging size problems with the box model diagram

Most size problems are box model problems in disguise. An element that is wider than expected usually has padding or a border added to its width under content-box sizing, or a child that is wider than its parent. An element that is narrower than expected usually has a width set on the wrong box, or a parent that constrains it. The developer tools box model diagram settles the question in seconds, because it lists the exact size of each layer.

Work through a size problem in a fixed order. First, read the diagram and confirm the content size, the padding, the border and the margin. Second, check the box-sizing value in effect, because a stylesheet or a framework may have changed it. Third, look at the children, since a child with a fixed width can force a parent wider even when the parent has no width of its own. Fourth, check the parent, since a parent with a fixed width limits every child inside it.

Write that order down and use it every time, because guessing at size problems by changing values at random tends to create a second problem while the first one is still unsolved. A measured approach also builds the habit of reading the diagram before editing the stylesheet, which is the skill that transfers to every layout problem after this one.

Frequently asked questions

Why is my element wider than the width I set?

That usually happens because padding and border are added to the width under the default box model. Setting box-sizing to border-box on the element makes the width include padding and border, which often matches what you expected when you set the width.

Should I use margin or padding to create space?

Use padding for space inside an element, between its border and its content. Use margin for space outside an element, between it and its neighbours. That distinction keeps the background and border behaviour clear, and it makes later changes easier to predict.

Does the box model apply to every element?

Block level elements follow the box model in a straightforward way. Inline elements also have padding and margins, but vertical margins and some sizing behaviour work differently, so the result can surprise you if you treat an inline element like a box. Checking the display type helps in those cases.

Why is my element wider than the width I set?

With content-box sizing, padding and border are added to the width you set, so the total is larger. Switching to border-box sizing makes the set width include padding and border, which removes the surprise for most layouts.

How do I stop a child margin from moving its parent?

Add padding or a border to the parent, so the child margin no longer collapses with the parent margin. Even one pixel of padding is enough to separate them, though a deliberate padding value usually reads better in the code.

Sources