CSS Margins
CSS margins are used to create space around HTML elements, outside of their borders. They allow you to control spacing between elements, improving layout and readability.
Margin Property
The margin property sets the space outside an element.
It can take values in pixels, percentages, em units, or auto.
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: 60px;
border:1px solid red;
}
</style>
</head>
<body>
<div>This is my first CSS page.</div>
</body>
</html>
Try this code
Individual Margins
You can set margins for each side of an element individually using:
margin-top, margin-right, margin-bottom, and
margin-left.
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin-top: 100px;
margin-right: 70px;
margin-bottom: 50px;
margin-left: 70px;
border:1px solid red;
}
</style>
</head>
<body>
<div>This is my first CSS page.</div>
</body>
</html>
Try this code
Shorthand Margin Property
You can use the shorthand margin property to set all four sides in one line:
<!DOCTYPE html>
<html>
<head>
<style>
/* top right bottom left */
div {
margin: 10px 15px 20px 25px;
}
</style>
</head>
<body>
<div>This is my first CSS page.</div>
</body>
</html>
Try this code
/* top right & left bottom */
div {
margin: 10px 20px 15px;
}
/* top & bottom, left & right */
div {
margin: 10px 20px;
}
/* all sides same */
div {
margin: 15px;
}
Auto Margin
Setting margin: auto; can be used to center block-level elements horizontally.
<!DOCTYPE html>
<html>
<head>
<style>
div.centered {
width: 50%;
margin:auto;
}
</style>
</head>
<body>
<div class="centered">This is my first CSS page.</div>
</body>
</html>
Try this code
Negative Margin
Margins can also be negative, allowing elements to overlap or move closer than normal spacing.
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin-top: -10px;
}
</style>
</head>
<body>
<div>This is my first CSS page.</div>
</body>
</html>
Try this code
Best Practices for Margins
- Use consistent margins to maintain a clean layout
- Prefer shorthand
marginwhen possible - Use auto margins to center content horizontally
- Be careful with negative margins to avoid layout issues
Common Mistakes with Margins
- Mixing too many margin values inconsistently
- Overusing negative margins causing overlap
- Not considering responsive layouts when setting fixed margins
margin with padding to create balanced spacing
for elements.