CSS Margins & Padding

Margin Individual Properties

This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.

Margin Shorthand Property - 4 values

This div element has a top margin of 25px, a right margin of 50px, a bottom margin of 75px, and a left margin of 100px.

Margin Auto Property

You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins:

This div will be horizontally centered because it has margin: auto;

Padding Individual Properties

This div element has a top padding of 50px, a right padding of 30px, a bottom padding of 25px, and a left padding of 80px.

Padding Shorthand Property - 4 values

This div element has a top padding of 25px, a right padding of 50px, a bottom padding of 50px, and a left padding of 100px.

Padding and Width

This div is 300px wide.

The width of this div is 350px, even though it is defined as 300px in the CSS.

The width of this div remains at 300px, in spite of the 50px of total left and right padding, because of the box-sizing: border-box property.

Height and Width

This div element has a height of 200px and a width of 50%

Height and Max Width

This div element has a height of 100px and a max-width of 500px.Resize the browser window to see the effect.

Outline

This element has a 2px black border and a green outline with a width of 10px.

CSS Box Model

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:

Box Model Image