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


Use the marginTop property in JavaScript, to set the top margin. Can you try to run the following code to set the top 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 top margin</button>
      <script>
         function display() {
            document.getElementById("myID").style.marginTop = "150px";
         }
      </script>
   </body>
</html>

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 24-Jan-2020

982 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements