Appling Margin to an Element
Margin is space between the element border and surroundings.
The margin properties are:
Property | Description | Values |
---|---|---|
margin-top | top margin | auto or <length> or <%> |
margin-right | right margin | auto or <length> or <%> |
margin-bottom | bottom margin | auto or <length> or <%> |
margin-left | left margin | auto or <length> or <%> |
margin | This shorthand property sets the margin for all edges. | auto, or <length>, or <%> |
auto means browser would do calcluation.
The percentage values of margin are always derived from the width of the containing block.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
img {
border: 4px solid black;
background: lightgray;
padding: 4px;
margin:4px 20px;
}
</style>
</head>
<body>
<img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="image"/>
<img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="background"/>
</body>
</html>
The following CSS uses auto as the margin value:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
img {
border: 4px solid black;
background: lightgray;
padding: 4px;
margin:auto;
}
</style>
</head>
<body>
<img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="image"/>
<img src="http://java2s.com/Book/HTML-CSSImages/star.png" alt="background"/>
</body>
</html>