Margins & Centring

Margins add a transparent area outside the border of an element.

Margins add to the total width and height of an element.

Specific Margins

Margins for each side can be set separately:

1
2
3
4
5
6
h1 {
    margin-top: 10px;
    margin-right: 5px;
    margin-bottom: 10px;
    margin-left: 5px;
}

Margin Shorthand

The margin shorthand property can have different numbers of values.

4 values = top – right – bottom – left

1
2
3
h1 {
    margin: 10px 5px 10px 5px;
}

3 values = top – left & right – bottom

1
2
3
h1 {
    margin: 10px 5px 10px;
}

2 values = top & bottom – left & right

1
2
3
h1 {
    margin: 10px 5px;
}

1 value = top & bottom & left & right

1
2
3
h1 {
    margin: 10px;
}

Centring

Using a value of “auto” will centre an element inside the browser window, or its containing element

1
2
3
h1 {
    margin: auto;
}