Javascript DOM CSS Style margin Property

Introduction

Set all four margins of a <div> element:

document.getElementById("myDiv").style.margin = "50px 10px 20px 30px";

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {//from   w w w .ja  va  2  s .c om
  border: 1px solid #FF0000;
}
</style>
</head>
<body>

<div id="myDiv">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">Set margin</button>

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

</body>
</html>

The margin property sets or gets the margins of an element.

This property can take from one to four values:

Value Count Example Description
One value div {margin: 50px} all four margins will be 50px
Two valuesdiv {margin: 50px 10px} the top and bottom margins will be 50px, left and right margins will be 10px
Three valuesdiv {margin: 50px 10px 20px} the top margin will be 50px, left and right margin will be 10px, bottom margin will be 20px
Four valuesdiv {margin: 50px 10px 20px 30px}the top margin will be 50px, right margin will be 10px, bottom margin will be 20px, left margin will be 30px

Both the margin property and the padding property insert space around 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 margins in % of the width of the parent element
length Sets the margins in length units
autoThe browser sets the margins
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

The margin property Default Value:0

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




PreviousNext

Related