The CSS margin properties allow you to set the spacing around the border of an element's box (or the edge of the element's box, if it has no defined border).
An element's margin is not affected by its background-color, it is always transparent. However, if the parent element has the background color it will be visible through its margin area.
You can specify the margins for the individual sides of an element such as top, right, bottom, and left sides using the CSS margin-top, margin-right, margin-bottom, and the margin-left properties, respectively. Let's try out the following example to understand how it works:
The margin properties can be specified using the following values:
You can also specify negative margins on an element, e.g., margin: -10px;, margin: -5%;, etc.
The margin property is a shorthand property to avoid setting margin of each side separately, i.e., margin-top, margin-right, margin-bottom and margin-left.
Let's take a look at the following example to understand how it basically works:
This shorthand notation can take one, two, three, or four whitespace separated values.
It is recommended to use the shorthand properties, it will help you to save some time by avoiding the extra typing and make your CSS code easier to follow and maintain.
The auto value for the margin property tells the web browser to automatically calculate the margin. This is commonly used to center an element horizontally within a larger container.
Let's try out the following example to understand how it works:
The above style rules lets the < div> element take up 300 pixels of all the horizontal space available, and the remaining space will be equally divided between left and right margins.