Skip to main content

The CSS Box Model

Talk about design and layout in CSS and the term box model soon comes up.

It describes a box wrapped around every HTML element, made of four parts: content, padding, border, and margin.

  • Content — holds the text and images.
  • Padding — a transparent area cleared around the content.
  • Border — surrounds both padding and content.
  • Margin — a transparent area cleared beyond the border.

Thanks to this model, we can put a border around elements and control the space between them.

Example

Each part of the box is visible on this div, which has a width, a green border, padding, and a margin.

Prompt
An HTML page that demonstrates the CSS box model on a single element. In an internal <style> block, give a <div> width 300px, a 15px solid green border, 50px padding, and 20px margin. Add a background color so the content area is visible. Put text inside.
Output: complete HTML page

Width and Height of an Element

Getting width and height right in all browsers depends on understanding the box model.

Important: The width and height properties only size the content area. Padding and borders come on top, so add them to find the total size.

Total width = width + padding on the left and right + border on the left and right.

Total height = height + padding on the top and bottom + border on the top and bottom.

Note: The box's size ends at the border. A margin is not part of that size, though it does add to the space the box occupies on the page.

Example

Start from a width of 320px with 10px padding and a 5px border: the result is 350px of total width and 80px of total height.

Prompt
An HTML page that shows how padding and border add to an element's total size. In an internal <style> block, give a <div> width 320px, height 50px, padding 10px, a 5px solid gray border, and margin 0. The total width becomes 350px and the total height 80px. Put text inside.
Output: complete HTML page