/

HTML / CSS / JavaScript Tutorial

CSS Property: margin

[this page | pdf | back links]

The CSS (CSS1) margin property is a shorthand property combining all four margin properties. The individual margin widths can be set separately using margin-bottom, margin-left, margin-right and margin-top. As with some other aggregate edge properties, up to four parameter values can be supplied (and if more than one is supplied then the properties are applied to individual borders as described here).

 

Valid property values (other than inherit and initial) are defined by the elements of the shorthand. Shorthand elements included in the margin property are:

 

Value

Description

length

Any specified margin size as a CSS length

%

Margin specified as percentage of width of container

auto

Browser calculates margin

 

Default Value:

0

JavaScript syntax:

e.g. object.style.margin="25px 30px"

Inherited:

No

Animatable:

See individual properties

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
div {border: 2px solid red; width: 300px}
p {border: 2px solid green; width: 200px}
p.x1 {margin: 30px;}
</style>
</head>
<body>
Element with default property<br>
<div>a<p>1</p>b</div><br><br>
Property set using in-file HTML style<br>
<div>a<p class="x1">2</p>b</div><br><br>
Property set using JavaScript<br>
<div>a<p id="x2">3</p>b</div>

<script>
document.getElementById("x2").style.margin = "30px";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyMargin() {
  var x = document.createElement("DIV"); x.style.margin = "30px"; return (window.getComputedStyle(x, null).margin == "30px");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile