The CSS margin properties are used to create space around elements, outside of any defined borders.
The margin property defines the space around an HTML element. It is possible to use negative values to overlap content.
With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).
Top, bottom, left and right margin can be changed independently using separate properties. You can also change all properties at once by using shorthand margin property.
The values of the margin property are not inherited by the child elements. Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so that the distance between the blocks is not the sum of the margins, but only the greater of the two margins or the same size as one margin if both are equal.
We have the following properties to set an element margin.
To shorten the code, it is possible to specify all the margin properties in one property.The margin property allows you set all of the properties for the four margins in one declaration. Here is the syntax to set margin around a paragraph −
The margin-bottom property allows you set bottom margin of an element. It can have a value in length, % or auto.
The margin-top property allows you set top margin of an element. It can have a value in length, % or auto.
The margin-left property allows you set left margin of an element. It can have a value in length, % or auto.
The margin-right property allows you set right margin of an element. It can have a value in length, % or auto.
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 example lets the left margin of the <p class="ex1"> element be inherited from the parent element (<div>):
Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.This does not happen on left and right margins! Only top and bottom margins.Look at the following example: