CSS margins create empty space outside an element's border, separating the element from its neighboring elements on the web page layout.
Margins can be applied to all four sides simultaneously or individually (margin-top, margin-right, margin-bottom, margin-left):
/* Individual sides */
div {
margin-top: 20px;
margin-bottom: 30px;
}
/* Shorthand variants */
div { margin: 20px; } /* All 4 sides: 20px */
div { margin: 10px 20px; } /* Top/Bottom: 10px, Left/Right: 20px */
div { margin: 10px 20px 15px 5px; } /* Top: 10px, Right: 20px, Bottom: 15px, Left: 5px */
Key margin features:
margin: 0 auto;: Centering technique for block-level elements with a defined width or max-width.margin-top: -10px) pull elements closer or overlap them.flowchart TD
A["Element Box"] --> B["Outer Space: MARGIN (Outside Border)"]
A --> C["Border Boundary"]
A --> D["Inner Space: PADDING (Inside Border)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Margins Demonstration</title>
<style>
.centered-container {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
max-width: 500px;
margin: 2rem auto; /* Centered horizontally with 2rem top/bottom margin */
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 1rem;">
<div class="centered-container">
<h2>Horizontally Centered Block</h2>
<p>Using <code>margin: 2rem auto;</code> centers this box horizontally inside the body container.</p>
</div>
</body>
</html>
margin: 0 auto; for block centering: Requires an explicit max-width or width set on the block container.margin-bottom: 1rem;) based on a design grid.Write a CSS rule centering a .container element horizontally with margin: 0 auto; and a max-width: 800px!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.