CSS margin properties are used to create space around an HTML element. Margin can be set to any side of an element by using the following properties.
- margin-top
- margin-bottom
- margin-left
- margin-right
The margin of an element is transparent and the length of the margin can be specified in px, cm, mm or %.
margin-top:2px;
margin-bottom:3cm;
Exapmle
<html>
<head>
<title>CSS Margin<title>
<style>
h2{
margin-top:2cm;
margin-left:1cm;
border: 1px solid green;
}
<style>
</head>
<body>
<h2>CSS Margins</h2>
</body>
</html>
CSS Margins
Shorthand property
Instead of specifying the four margin properties as separate properties, you can specify them as a single margin property.
Example
margin: 10px 12px 15px 8px;
This is same as:
margin-top:10px;
margin-right:12px;
margin-bottom:15px;
margin-left:8px;
Specifying values
Method | Description |
margin: 2px; | This will set: margin-top:2px; margin-right:2px; margin-bottom:2px; margin-left:2px; |
margin: 1px 2px; | This will set: margin-top:1px; margin-right:2px; margin-bottom:1px; margin-left:2px; |
margin: 1px 2px 3px; | This will set: margin-top:1px; margin-left:2px; margin-right:2px; margin-bottom:3px; |
The margin can be set to auto (margin:auto;) to horizontally center the element within the parent element.
If the margin is set to inherit (margin: inherit), the margin of the element will be inherited from the parent element.
Subscribe
Join the newsletter to get the latest updates.