Javascript DOM CSS Style marginLeft Property

Introduction

Set the left margin of a <div> element:

document.getElementById("myDiv").style.marginLeft = "50px";

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {/*from ww  w  . j  a v  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 left margin</button>

<script>
function myFunction() {
  document.getElementById("myDiv").style.marginLeft = "50px";
}
</script>

</body>
</html>

The marginLeft property sets or gets the left 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 left margin in % of the width of the parent element
length Sets the left margin in length units
autoThe browser sets the left margin
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

The marginLeft property Default Value: 0

The marginLeft property returns a String representing the left margin of an element.




PreviousNext

Related