margin Property - Javascript CSS Style Property

Javascript examples for CSS Style Property:margin

Description

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

This shorthand notation can take one, two, three, or four whitespace separated values.

  • If one value is set, this margin sets all 4 sides.
  • If two values are set, the first value sets top and bottom, the second value sets the right and left side.
  • Three values set the top, horizontal (i.e. right and left) and bottom side.
  • Four values set the top, right, bottom, left side in that order.

Property Values

Value Description
% margins in percentage of the width of the parent element
length 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.

Technical Details

Item Value
Default Value: 0
Return Value: A String, representing the margins of an element
CSS VersionCSS1

Set all four margins of a <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {//from www  .ja  v a2  s  . c  o  m
    border: 1px solid #FF0000;
}
</style>
</head>
<body>

<div id="myDiv" style="margin-top:5cm;">This is a div.</div>
<br>
<button type="button" onclick="myFunction()">test</button>

<script>
function myFunction() {
    document.getElementById("myDiv").style.margin = '5px 5px 5px 5px';
}
</script>

</body>
</html>

Related Tutorials