In CSS, margins are used to add space around an HTML element. You can set the margin values using various CSS properties.
To set the margin of an element, you can use the margin
property. The value can be set to a specific size or you can use the following values: auto
, inherit
, initial
, unset
. Here’s an example:
div {
margin: 20px;
}
In the above example, the div
element will have a margin of 20 pixels around all sides.
You can also set the margin for individual sides using the following properties: margin-top
, margin-right
, margin-bottom
, and margin-left
. For example:
div {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 30px;
margin-left: 40px;
}
In the above example, the div
element will have a 10 pixel margin on the top, a 20 pixel margin on the right, a 30 pixel margin on the bottom, and a 40 pixel margin on the left.
You can also use negative margin values to bring elements closer together. For example:
div {
margin-top: -10px;
margin-left: -20px;
}
In the above example, the div
element will have a margin of -10 pixels on the top and -20 pixels on the left, which will bring the element closer to the element above and to the left.
In addition to these properties, you can also use the padding
property to add space within an element. The padding
property works similarly to the margin
property, but adds space within an element rather than around it.
Margins and padding can be used to create whitespace between elements, and to adjust the positioning of elements within a layout.