Techcss
Untitled Document

CSS Margins

The margin property sets the margin between an HTML element and the elements around it. The margin property can be set for the top, left, right and bottom of an element.

A margin property can have three types of values as


Declaring margin property individually for top, left, right, bottom

Example:

margin-top: 5px;
margin-left: 15%;
margin-right: auto;
margin-bottom: 5px;

Declaring margin property all in a single margin declaration

We can also declare all the margins of an element in a single property as
follows:
If we declare all 4 values as I have above, the sequence is as follows:
1. top
2. right
3. bottom
4. left

Example:

margin: 2px 10px 10px 5px;

If only one value is declared, it sets the margin on all sides. (see below)

margin: 12px;

If we only declare two or three values, the undeclared values are taken from the opposing side. (see below)

margin: 5px 15px; /* 2 values */
margin: 5px 5px 5px; /* 3 values */

We can set the margin property to negative values.

margin: -5px;

If we do not declare the margin value of an element, then the value is considered as '0'.

 

We do not have to mention any unit (px or whatever), if the value is '0'.