Web Development - CSS Spacing
CSS Spacing - Margins and Padding
Margins and padding control the spacing around and inside HTML elements. They help organize your layout and make your content easier to read.
What is Margin?
The margin is the space outside an element's border. It pushes the element away from its neighbors.
This adds 20px of space on all sides of the element.
What is Padding?
The padding is the space inside an element's border. It pushes the content away from the border.
Example
Using padding:
div {
padding: 20px;
background-color: lightgreen;
border: 2px solid black;
}
Try it Yourself »
This adds space between the element's content and its border.
Individual Sides
You can set margins and padding for each side separately:
margin-topmargin-rightmargin-bottommargin-leftpadding-toppadding-rightpadding-bottompadding-left
Example
Different values for each side:
div {
margin-top: 10px;
margin-right: 30px;
margin-bottom: 20px;
margin-left: 40px;
padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;
}
Try it Yourself »
Shorthand Properties
You can use shorthand syntax for both margin and padding.
Example
Shorthand margin and padding:
/* top, right, bottom, left */
div { margin: 10px 20px 30px 40px; }
/* vertical | horizontal */
p { padding: 10px 20px; }
/* all sides equal */
h1 { margin: 20px; padding: 10px; }
Try it Yourself »
Margin Auto
You can center block elements horizontally by setting margin: auto;.
Example
Centering an element:
div {
width: 300px;
margin: auto;
border: 1px solid black;
padding: 10px;
}
Try it Yourself »
Margin Collapse
When two vertical margins meet, they may collapse into a single margin (the larger of the two).
Example
Collapsing margins:
<h1 style="margin-bottom: 50px;">Heading</h1>
<p style="margin-top: 20px;">Paragraph</p>
Try it Yourself »
Note: Only vertical (top and bottom) margins can collapse. Padding never collapses.
Padding and Background
Padding adds space inside the element and expands the background color or image along with it.
Example
Background expands with padding:
div {
background-color: lightcoral;
padding: 20px;
}
Try it Yourself »
Best Practices
- Use margins for outer spacing between elements.
- Use padding for inner spacing within elements.
- Use shorthand to simplify code.
- Use
margin: auto;for centering blocks horizontally. - Remember: only vertical margins can collapse.
Next, you'll learn about the CSS Box Model - how margins, borders, padding, and content work together to form every element on a web page.