Set the top margin of an element 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 top edge.

Syntax

margin-top: value;

The value can be specified in pixels (px), percentages (%), em units, or set to auto for automatic margin calculation.

Example

<html>
   <head>
      <title>CSS margin-top Example</title>
   </head>
   <body>
      <p style="margin-top: 10px; border: 2px solid red; padding: 5px;">
         This paragraph has a 10px top margin
      </p>
      
      <p style="margin-top: 5%; border: 2px solid green; padding: 5px;">
         This paragraph has a 5% top margin (relative to container)
      </p>
      
      <p style="margin-top: 2em; border: 2px solid blue; padding: 5px;">
         This paragraph has a 2em top margin
      </p>
   </body>
</html>

Common Values

Value Description Example
Pixels (px) Fixed margin size margin-top: 20px;
Percentage (%) Relative to parent width margin-top: 10%;
Em units Relative to font size margin-top: 1.5em;
Auto Browser calculates margin margin-top: auto;

Negative Margins

You can also use negative values to pull elements upward, overlapping with elements above:

<div style="background: lightgray; padding: 10px; margin-bottom: 20px;">
   First element
</div>

<div style="background: lightblue; padding: 10px; margin-top: -10px;">
   Second element with negative top margin (overlaps above)
</div>

Conclusion

The margin-top property controls spacing above elements. Use positive values to create space, negative values for overlap, and percentage values for responsive layouts.

Updated on: 2026-03-15T23:18:59+05:30

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements