← Web basics: HTML, CSS and JavaScript

The box model

Every element is a box: content, padding, border and margin.

Start this lesson

To a browser, every element is a rectangle made of layers, like a framed picture. In the middle is the content (the text or image). Around it is padding, space inside the frame. Then the border, the frame itself. Outside the border is margin, space that pushes other boxes away. Padding takes the element's background color; margin is always see-through. Knowing which layer to change is the key to spacing things nicely.

.card {
  padding: 16px;
  border: 2px solid #444;
  margin: 24px;
  background-color: white;
}
.tag {
  padding: 4px 10px;
}

The card has 16px of white space inside its border on every side, a 2px dark border, and 24px of empty space outside it. The tag uses two values: 4px top and bottom, 10px left and right.

With four values the order is clockwise from the top: padding: 1px 2px 3px 4px means top 1, right 2, bottom 3, left 4. You can also set one side, like margin-top: 10px.

border takes three parts: width, style (solid, dashed, dotted) and color. border-radius rounds the corners.

Adding box-sizing: border-box makes width include padding and border, which makes sizes much easier to predict. Many sites set it on every element.