Spacing Elements
Margins create space around elements, outside of any defined borders.
Padding creates space around an element's content, inside of any defined borders.
/* Margin - All sides */
div {
margin: 20px;
}
/* Margin - Individual sides */
p {
margin-top: 10px;
margin-right: 20px;
margin-bottom: 10px;
margin-left: 20px;
}
/* Margin - Shorthand */
h1 {
margin: 10px 20px 10px 20px; /* top right bottom left */
}
/* Padding works the same way */
.box {
padding: 15px;
}
- margin - Space outside border
- padding - Space inside border
- Can set all sides or individual sides
- Shorthand: top, right, bottom, left
- Auto value centers elements
Try Margins and Padding
<div class="box1">Box with padding</div>
<div class="box2">Box with margin</div>
<div class="box3">Box with both</div>
Note: Use margin: 0 auto to center block elements horizontally.