Margins in the CSS Box Model (Live Playground)
Margins are an essential component of the CSS box model, creating space between the border of an element and surrounding elements. In this tutorial, you will learn about margins, how to set individual and shorthand margin properties, and how they affect the layout of elements, along with sample code and simple explanations.
Individual margin properties
You can set margins individually for each side of an element using the following properties:
margin-top
margin-right
margin-bottom
margin-left
Example:
div {
background-color: lightblue;
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
}
<div>This div element has individual margin values for each side.</div>
In this example, the div
element has 10px margin on the top and bottom and 20px margin on the left and right.
Shorthand margin property
The shorthand margin
property allows you to set margins for all four sides in a single line of code:
margin: top right bottom left;
margin: top/bottom left/right;
margin: top left/right bottom;
margin: all;
Example:
div {
background-color: lightblue;
margin: 10px 20px;
}
<div>This div element has shorthand margin values for all sides.</div>
In this example, the div
element has 10px margin on the top and bottom and 20px margin on the left and right using the shorthand margin property.
The effect of margins on layout
Margins affect the total size of an element and can influence the positioning of surrounding elements. They do not, however, affect the size of the content area, padding, or border.
Example:
.container {
display: flex;
}
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin-right: 10px;
}
.box-margin {
margin: 20px;
}
<div class="container">
<div class="box">No margin</div>
<div class="box box-margin">With margin</div>
</div>
In this example, the div
element with margin has a larger total size but retains the same content size, padding, and border as the div
element without margin.
Conclusion
In this tutorial, you learned about margins in the CSS box model and how to set individual and shorthand margin properties. By understanding the role of margins in the box model and how they affect the layout of elements, you can create more visually appealing and consistent designs across your web pages.