How to set the right margin of an element with JavaScript?

Use the marginRight property in JavaScript to set the right margin of an element. This property accepts values in pixels, percentages, or other CSS units.

Syntax

element.style.marginRight = "value";

Example

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myID {
        border: 2px solid #000000;
        background-color: #f0f0f0;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    This is demo text.<br>
    <button type="button" onclick="display()">Add right margin</button>
    <script>
      function display() {
        document.getElementById("myID").style.marginRight = "150px";
      }
    </script>
  </body>
</html>

Setting Different Values

You can set various margin values using different units:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .demo-box {
        border: 2px solid #333;
        background-color: #e8f4fd;
        padding: 10px;
        margin: 10px 0;
      }
    </style>
  </head>
  <body>
    Pixels: 50px
    Percentage: 10%
    Em units: 3em
    
    <button onclick="setMargins()">Set Different Margins</button>
    
    <script>
      function setMargins() {
        document.getElementById("box1").style.marginRight = "50px";
        document.getElementById("box2").style.marginRight = "10%";
        document.getElementById("box3").style.marginRight = "3em";
      }
    </script>
  </body>
</html>

Common Use Cases

Value Description Example
Pixels Fixed margin size "20px"
Percentage Relative to parent width "15%"
Em units Relative to font size "2em"
Auto Browser calculates margin "auto"

Conclusion

The marginRight property provides a simple way to dynamically adjust right margins. Use appropriate units based on your layout requirements for responsive design.

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

671 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements