CSS Tutorial

Introduction

Edit Template

CSS Tutorial

Introduction

Edit Template

CSS Margin

Margins define the outer space around HTML elements. It’s like giving each element its own breathing room, separating it from others on the page..

What Is Margin?

Margin is the space outside the border of an element.

If padding is the inner space, margin is the external space that pushes other elements away.

Basic Syntax

				
					selector {
  margin: value;
}

				
			

You can set margins using:

  • px (pixels)
  • em, rem
  • % (percentage)
  • auto (useful for centering)

Method 1: Same Margin on All Sidess

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .box {
      border: 2px dashed #2c3e50;
      margin: 20px;
      background-color: #fefae0;
    }
  </style>
</head>
<body>
  <div class="box">All sides have 20px margin</div>
</body>
</html>

				
			
Equal Margin Example

Explanation:
The box moves away from all surrounding elements by 20px.

Method 2: Vertical and Horizontal Margins

				
					selector {
  margin: vertical horizontal;
}

				
			
				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .alert {
      border: 1px solid #e67e22;
      margin: 30px 60px;
      background-color: #fff4e6;
    }
  </style>
</head>
<body>
  <div class="alert">Top & Bottom: 30px — Left & Right: 60px</div>
</body>
</html>

				
			
Vertical and Horizontal Margin Example

Tip: This layout is helpful when you want more horizontal spacing than vertical.

Method 3: Margins on All Sides Individually

				
					selector {
  margin: top right bottom left;
}


				
			
				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .card {
      margin: 10px 40px 20px 80px;
      border: 2px solid #6c5ce7;
      background-color: #dfe6e9;
    }
  </style>
</head>
<body>
  <div class="card">Custom margins: top-10px, right-40px, bottom-20px, left-80px</div>
</body>
</html>

				
			
Custom Margin Example

Breakdown:

  • Top → 10px

  • Right → 40px

  • Bottom → 20px

  • Left → 80px

Bonus Tip: Centering with Margin Auto

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .centered {
      width: 300px;
      margin: 0 auto;
      text-align: center;
      border: 2px solid #27ae60;
      background-color: #eafaf1;
    }
  </style>
</head>
<body>
  <div class="centered">I'm centered using margin: 0 auto</div>
</body>
</html>

				
			
Centered Margin Example
Scroll to Top