Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Usage of margin property with CSS
The CSS margin property defines the space around an HTML element, creating transparent area outside the element's border. It is possible to use negative values to overlap content and it serves as a shorthand property for setting all margin properties in one declaration.
Syntax
selector {
margin: value;
}
Possible Values
| Value | Description |
|---|---|
length |
Defines margin in px, em, rem, etc. |
% |
Defines margin as percentage of container width |
auto |
Browser calculates the margin automatically |
inherit |
Inherits margin from parent element |
Example 1: Single Value Margin
The following example applies 20px margin to all four sides −
<!DOCTYPE html>
<html>
<head>
<style>
.single-margin {
margin: 20px;
border: 2px solid #4CAF50;
background-color: #f0f8f0;
padding: 10px;
}
</style>
</head>
<body>
<p class="single-margin">
All four margins will be 20px
</p>
</body>
</html>
A paragraph with green border and light green background appears with 20px spacing on all sides from the browser edge.
Example 2: Multiple Value Margin
This example demonstrates using three values for top, left/right, and bottom margins −
<!DOCTYPE html>
<html>
<head>
<style>
.multi-margin {
margin: 15px 4% -10px;
border: 2px solid #ff6b6b;
background-color: #ffe0e0;
padding: 10px;
}
body {
margin: 0;
padding: 20px;
}
</style>
</head>
<body>
<p class="multi-margin">
Top margin: 15px, Left/Right margin: 4%, Bottom margin: -10px
</p>
<p style="border: 1px solid #ccc; margin: 0; background-color: #f9f9f9;">
This paragraph shows the negative bottom margin effect
</p>
</body>
</html>
The first paragraph has red border with 15px top margin, 4% left and right margins, and -10px bottom margin. The second paragraph overlaps slightly due to the negative margin, demonstrating the overlapping effect.
Conclusion
The margin property is essential for controlling spacing around elements. You can use 1-4 values to control different sides, and negative values create overlapping effects for advanced layouts.
Advertisements
