CSS Margins
The margin
property in CSS is used to create space around elements, outside of any defined borders. You can set the margins for each side of an element (top, right, bottom, and left) or use the shorthand property to set all four sides at once.
Margin Properties
Here are the main properties used to set margins in CSS:
margin-top
– Sets the top margin of an element.margin-right
– Sets the right margin of an element.margin-bottom
– Sets the bottom margin of an element.margin-left
– Sets the left margin of an element.margin
– Shorthand property for setting all four margins at once.
Examples
Individual Margins
You can set individual margins using the margin-top
, margin-right
, margin-bottom
, and margin-left
properties.
div {
margin-top: 20px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 15px;
}
Shorthand Margin Property
The margin
shorthand property can be used to set all four margins at once. The values are applied in the order: top, right, bottom, left.
div {
margin: 20px 15px 20px 15px;
}
Auto Margin
Using margin: auto;
can be useful for centering elements horizontally.
div {
width: 50%;
margin: auto;
}
margin: auto;
.
Conclusion
The margin
property in CSS is essential for controlling the layout and spacing of elements on a webpage. By adjusting the margins, you can create visually appealing and well-structured designs.