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


Use the marginRight property in JavaScript, to set the right margin. You can try to run the following code to set the right margin of an element with JavaScript −

Example

Live Demo

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

Updated on: 23-Jun-2020

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements