Press key to advance. Zoom in/out: Ctrl or Command + +/-.

CSS: Box Model

The Box Model

All elements are treated as boxes by the browser's rendering engine (either "inline" or "block" boxes).

A box consists of content, padding, border, and margin:


The margin is a transparent area around the box - the background of the box does not apply to it. It separates the box from other elements.

15 pixels on all sides:

margin: 15px;

10px on top, 5px right, 3px bottom, 20px left:

margin: 10px 5px 3px 20px;

10px on top:

margin-top: 10px;

Auto Margin

If the margin is set to "auto" on a box that has a width, it will take up as much space as possible.

A centered box:

<div style="margin:auto; width:300px;">Hi</div>

A flush-right box:

<div style="margin-left:auto; margin-right:5px;
  width:300px;"> Hi</div>


The border property styles the edge around the box and is specified as "thickness style color".

A solid red border:

border: 1px solid #ff0000;

A thick dotted black top border:

border-top: 4px dotted #000000;

2 different border styles:

border-top: 4px dotted #000000;
border-bottom: 1px solid #ff0000;

Border Thickness

Border thickness can also be specified with border-width property and can be different on each side (like margin).

10px on all sides:

border-width: 10px;

10px on top, 5px right, 3px bottom, 20px left:

border-width: 10px 5px 3px 20px;

Border Style

Border style can also be specified using the border-style property.


Border Color

Border color can also be specified with border-color property.

Green on all sides:

border-color: rgb(0, 240, 0);

White on top, black right, red bottom, green left:

border-color: #fff black #ff0000 #00ff00;


The padding property specifies whitespace between the border and the content.

15px on all sides:

padding: 15px;

10px on top, 5px right, 3px bottom, 20px left:

padding: 10px 5px 3px 20px;

10px on top:

padding-top: 10px;