The margin property in CSS is used to create space around an element, outside of any defined borders. It can be used to set the margin for each side of an element (top, right, bottom, and left), or for all four sides at once.
The CSS margin property is used to set the margin for all four sides (top, right, bottom, left) of an element. The basic syntax is as follows:
selector {
margin: top right bottom left;
}
You can set the margin using different units such as pixels (px), ems (em, rem), percentages (%), and more.
If you want all four margins to have the same value, you can simply provide one value:
div {
margin: 20px; /* Applies 20px margin to all sides of the div */
background: red;
width: 400px;
height: 400px;
}
If you want to set the top and bottom margins to one value, and the right and left margins to another value, you can use the following syntax:
div {
margin: margin: 10px 20px; /* Top and bottom have 10px margin, left and right have 20px margin */
background: green;
width: 400px;
height: 400px;
}
You can also set margins for each side individually:
div {
margin-top: 30px;
margin-right: 10px;
margin-bottom: 20px;
margin-left: 5px;
background: green;
width: 400px;
height: 400px;
}
You can mix shorthand and individual margin properties. When using shorthand, any individual margin properties not specified will be set to their default value (usually 0).
div {
margin: 10px 20px; /* Top and bottom have 10px margin, left and right have 20px margin */
margin-bottom: 30px; /* Override the shorthand and set the bottom margin to 30px */
background: green;
width: 400px;
height: 400px;
}
You can use auto in the shorthand property to horizontally center a block-level element within its container.
.container {
width: 800px; /* Set the width of the container */
height: 800px;
background: green;
}
.centered-content {
width: 400px; /* Set the width of the element you want to center */
height: 400px;
margin: 0 auto; /* Horizontally center the element within the container */
background: blue;
}
Negative margins are used to overlap elements or reduce the space between them. Exercise caution when using negative margins, as they can lead to unexpected layouts.
div {
margin: -10px 0 0 -10px;
background: blue;
width: 400px;
height: 400px;
}