CSS Margins
Margins create space outside elements, pushing them away from other elements or the page edges. By adjusting margins, you can control the visual spacing and overall layout of your design. Margins are transparent and do not have a background color, allowing the page’s background or underlying elements to show through.
Key Topics
Setting Margins
Use margin
to set space around an element. For example, margin: 20px;
applies 20px of margin on all sides. You can also specify values for each side: margin: 10px 20px 15px 5px;
(top, right, bottom, left).
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Margin Example</title>
<style>
.box {
background-color: #ddd;
padding: 20px;
margin: 20px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div class="box">
<h2>Box with Margin</h2>
<p>This box has a 20px margin, providing space between it and other elements.</p>
</div>
</body>
</html>
Explanation: The margin separates the box from the page edges or nearby elements, preventing elements from being cramped together.
Individual Sides
Use margin-top
, margin-right
, margin-bottom
, and margin-left
to control margins per side. This gives you fine-grained control over spacing.
Auto Margins for Centering
For block-level elements with a fixed width, setting margin: 0 auto;
horizontally centers them in their parent container.
Key Takeaways
- Spacing: Margins add space outside an element’s border.
- Flexible: Control each side independently or set all sides at once.
- Centering: Use
auto
margins to center elements horizontally. - Layout: Margins help define the overall visual structure and readability of your page.