Search
Close this search box.
Course Content
CSS Basic
0/1
CSS Selectors
0/1
CSS Comments
0/1
CSS Backgrounds
0/1
CSS Borders
0/1
CSS Outline
0/1
CSS Fonts
0/1
CSS Height and Width
0/1
CSS Margins and Paddings
0/2
CSS Icons
0/1
CSS Links
0/1
CSS Lists
0/1
CSS Tables
0/1
CSS Display Properties
0/1
CSS Max-Width Property
0/1
CSS Positioning Elements
0/1
CSS Z-Index Property
0/1
CSS Overflow
0/1
CSS Float
0/1
CSS Opacity
0/1
CSS Forms
0/1
CSS Dropdowns
0/1
CSS Buttons
0/1
CSS Media Queries
0/1
About Lesson

Definition:

In CSS, the margin property is used to control the space outside an element’s border. It defines the amount of space between an element’s border and surrounding elements.

Syntax:

selector {
margin: value;
}

The value can be set using various units, such as pixels (px), em, rem, percentages (%), etc. You can also specify values for individual sides (top, right, bottom, left) using the margin-top, margin-right, margin-bottom, and margin-left properties.

Example:

<!DOCTYPE html>
<html lang=”en”>
<head>
  <meta charset=”UTF-8″>
  <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
  <style>
    /* Apply margin to a div with the class ‘box’ using shorthand property */
    .box {
      margin: 20px; /* Applies 20px margin to all sides */
      background-color: lightblue;
      padding: 10px;
      border: 2px solid navy;
    }
    /* Apply margin to a paragraph with the class ‘paragraph’ using individual properties */
    .paragraph {
      margin-top: 10px;
      margin-right: 30px;
      margin-bottom: 10px;
      margin-left: 30px;
      background-color: lightgreen;
      padding: 10px;
      border: 2px solid darkgreen;
    }
  </style>
  <title>Margin Example</title>
</head>
<body>
  <div class=”box”>
    This is a box with margin applied using the shorthand property.
  </div>
  <p class=”paragraph”>
    This is a paragraph with margin applied individually for each side.
  </p>
</body>
</html>

In this example:

  • The first CSS rule applies a margin of 20px to all sides of a div element with the class box. It also sets a light blue background, padding, and a navy border.

  • The second CSS rule applies different margins to each side of a p element with the class paragraph. It sets a light green background, padding, and a dark green border.

You can customize the margin values to create the desired spacing around your elements. Using the shorthand property is common for applying equal margins to all sides, while individual properties offer more control over each side’s margin.

Output: