How to set the bottom margin of an element?

The margin-bottom property sets the bottom margin of an element, creating space between the element and content below it. It accepts values in pixels, percentages, or auto.

Syntax

element.style.marginBottom = "value";

Parameters

The margin-bottom property accepts the following values:

  • Length: Pixels (px), em, rem, etc.
  • Percentage: Relative to parent element's width
  • auto: Browser calculates the margin automatically

Example: Setting Bottom Margin with CSS

<html>
<head>
    <style>
        .large-margin {
            margin-bottom: 40px;
            border: 2px solid yellow;
            padding: 10px;
        }
        .percentage-margin {
            margin-bottom: 20%;
            border: 2px solid yellow;
            padding: 10px;
        }
    </style>
</head>
<body>
    <p class="large-margin">
        Cricket crazy nation India!
    </p>
    <p class="percentage-margin">
        Cricket crazy nation Australia!
    </p>
    <p style="border: 2px solid green; padding: 10px;">
        This paragraph shows the margin effect above.
    </p>
</body>
</html>

Example: Setting Bottom Margin with JavaScript

<html>
<head>
</head>
<body>
    <p id="para1" style="border: 2px solid blue; padding: 10px;">
        Original paragraph with no bottom margin.
    </p>
    <p style="border: 2px solid green; padding: 10px;">
        This paragraph will have space above it after clicking the button.
    </p>
    
    <button onclick="setBottomMargin()">Set Bottom Margin</button>
    
    <script>
        function setBottomMargin() {
            document.getElementById("para1").style.marginBottom = "30px";
        }
    </script>
</body>
</html>

Common Use Cases

  • Spacing elements: Creating consistent vertical spacing between paragraphs
  • Layout design: Controlling whitespace in page layouts
  • Responsive design: Using percentages for fluid spacing

Conclusion

The margin-bottom property is essential for controlling vertical spacing in web layouts. Use pixels for fixed spacing or percentages for responsive designs.

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

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements