The margin property controls spacing outside the border of an element.
div {
margin: 20px;
}You can target specific sides of an element:
div {
margin-top: 10px;
margin-right: 15px;
margin-bottom: 30px;
margin-left: 5px;
}Use shorthand to combine multiple margin values:
/* Top, Right, Bottom, Left */
div {
margin: 10px 20px 30px 40px;
}To center a block element horizontally, set margin: 0 auto and define a width.
div {
width: 300px;
margin: 0 auto;
}When two vertical margins meet, only the larger margin is used. This is known as margin collapsing.
<p style="margin-bottom: 30px;">Paragraph 1</p>
<p style="margin-top: 50px;">Paragraph 2</p>Despite the combined values, the space between them will be 50px, not 80px.
Create two stacked elements and experiment with their vertical margins. Try changing:
overflow: hidden to one element to prevent collapsing<p style="margin-bottom: 30px;">First Paragraph</p>
<p style="margin-top: 50px;">Second Paragraph</p>You can copy and paste this code in your IDE to run!
Ask the AI if you need help understanding or want to dive deeper in any topic