CSS Margins

CSS Margins


CSS Margin
The margin is the space between an element’s border and other elements. 
The value of the margin property can be a size value, a percentage, or the keyword auto. 
By default, most elements have no margin. 
Syntax - 
Margin property is used to give margin to the elements.
Margin: value
As we have said by default elements take no margine now we will see examples - 
Example - 
<style>
.fruit {
border: 5px solid red;
width: 10rem;
}
.apple {
border: 5px solid green;
}
</style>
<div class="fruit">
<div class="apple">Hello world!</div>
</div>
Output - 
Now adding margin to the above example - 
<style>
.fruit {
border: 5px solid red;
width: 10rem;
}
.apple {
border: 5px solid green;
margin: 1rem;
}
</style>
<div class="fruit">
<div class="apple">Hello world!</div>
</div>

 
Output - 
Direction-Specific Properties - 
CSS allows you to specify a given side to apply margin to. The four properties provided for this purpose are - 
  • margin-left 
  • margin-right 
  • margin-top 
  • Margin-bottom
The standard margin property can be expanded to specify differing widths to each side of the selected elements. The syntax for doing this is as follows - 
margin: <top> <right> <bottom> <left>;
Now we will see example - 
Example - 
#myDiv { 
margin-left: 30px;
height: 40px;
width: 40px;
background-color: red; 
}
 
<div id="myDiv"></div>
Explanation - 
margin-left The direction in which the margin should be applied.
30px The width of the margin.
Margin Auto value - 
The margin property also accepts the auto value. 
When the horizontal (left and right) margin is set to auto in a block or inline-block element, the element is centered horizontally within its containing element. 
The element takes up the specified width, and the margin is automatically distributed evenly between the left and right margins. 
Now we will see Example  -
Example - 
<style>
.container {
background-color: red;
height: 5rem;
padding: 1rem;
width: 20rem;
}
.inner {
background-color: blue;
height: 3rem;
margin: auto;
width: 5rem;
}
</style>
<div class="container">
<div class="inner"></div>
</div>
Output -