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-right property with CSS
The CSS margin-right property specifies the right margin of an element. It controls the space between the element and adjacent elements or the container's edge on the right side.
Syntax
selector {
margin-right: value;
}
Possible Values
| Value | Description |
|---|---|
length |
Defines margin in px, em, rem, etc. |
% |
Defines margin as a percentage of parent element's width |
auto |
Browser calculates the margin automatically |
Example 1: Using Length Values
The following example demonstrates margin-right using pixel values −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
background-color: #f0f0f0;
padding: 10px;
}
.box1 {
margin-right: 50px;
padding: 10px;
background-color: #ff6b6b;
color: white;
}
.box2 {
margin-right: 20px;
padding: 10px;
background-color: #4ecdc4;
color: white;
}
</style>
</head>
<body>
<div class="container">
<div class="box1">Box with 50px right margin</div>
<div class="box2">Box with 20px right margin</div>
</div>
</body>
</html>
A gray container with two colored boxes inside. The red box has 50px space on its right side, and the teal box has 20px space on its right side.
Example 2: Using Percentage Values
The following example shows margin-right with percentage values −
<!DOCTYPE html>
<html>
<head>
<style>
.parent {
width: 400px;
background-color: #e8e8e8;
padding: 15px;
}
.child1 {
margin-right: 10%;
padding: 15px;
background-color: #ff9ff3;
color: white;
margin-bottom: 10px;
}
.child2 {
margin-right: 25%;
padding: 15px;
background-color: #54a0ff;
color: white;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1">10% right margin</div>
<div class="child2">25% right margin</div>
</div>
</body>
</html>
A light gray parent container with two boxes. The pink box has a right margin of 10% of the parent's width, and the blue box has a right margin of 25% of the parent's width.
Conclusion
The margin-right property is essential for controlling spacing and layout. Use pixels for fixed spacing or percentages for responsive designs that adapt to different container sizes.
Advertisements
