Set the top margin of a <div> element:
document.getElementById("myDiv").style.marginTop = "50px";
<!DOCTYPE html> <html> <head> <style> #myDiv {// w w w . j av a 2s .com border: 1px solid #FF0000; } </style> </head> <body> <div id="myDiv">This is a div.</div> <br> <button type="button" onclick="myFunction()">Set top margin</button> <script> function myFunction() { document.getElementById("myDiv").style.marginTop = "50px"; } </script> </body> </html>
The marginTop property sets or gets the top margin of an element.
The margin inserts the space around the border.
The padding inserts the space within the border of an element.
Property Values
Value | Description |
---|---|
% | Sets the top margin in % of the width of the parent element |
length | Sets the top margin in length units |
auto | The browser sets the top margin |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
The marginTop property default Value: 0
The marginTop property returns a String representing the top margin of an element.