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-top property with CSS
The margin-top property specifies the top margin of an element in CSS. It creates space above an element, pushing it away from adjacent elements or the container's edge.
Syntax
margin-top: value;
Values
-
Length: Fixed values like
10px,2em,1rem -
Percentage: Relative to parent's width (e.g.,
10%) - auto: Browser calculates automatically
- inherit: Inherits from parent element
Example: Fixed Values
<!DOCTYPE html>
<html>
<head>
<style>
.box1 {
margin-top: 20px;
border: 2px solid red;
padding: 10px;
}
.box2 {
margin-top: 50px;
border: 2px solid blue;
padding: 10px;
}
</style>
</head>
<body>
<div class="box1">Box with 20px top margin</div>
<div class="box2">Box with 50px top margin</div>
</body>
</html>
Example: Percentage Values
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 400px;
border: 1px solid black;
padding: 10px;
}
.percent-margin {
margin-top: 10%;
border: 2px solid green;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<p>First paragraph</p>
<p class="percent-margin">Paragraph with 10% top margin</p>
</div>
</body>
</html>
Comparison of Values
| Value Type | Example | Use Case |
|---|---|---|
| Fixed (px, em) | margin-top: 20px; |
Consistent spacing |
| Percentage | margin-top: 5%; |
Responsive designs |
| Auto | margin-top: auto; |
Automatic spacing |
Key Points
- Percentage values are calculated relative to the parent element's width, not height
- Negative values are allowed and pull elements upward
- Adjacent vertical margins collapse (margin collapsing)
- Works on block-level and inline-block elements
Conclusion
The margin-top property controls spacing above elements. Use fixed values for consistent layouts and percentages for responsive designs.
Advertisements
