In CSS the margin is the outermost layer of HTML elements, it adds space around them as opposed to padding which adds space inside an element, around its content. With CSS we can be very precise with margins.
Specifying the sides for CSS margin:
We can set different margins to the individual sides of an HTML element. We can set:
- margin-top
- margin-right
- margin-bottom
- margin-left
Acceptable values for margin:
- auto – the browser will calculate the margin (mostly used to center an element horizontally within its container)
- length – pixel, em, rem etc.
- percent – calculates the margin in percentages relative to the inline size of the containing element
- inherit – inherits the value from the parent element
Margin shorthands
There are different ways to specify the values for margin. We can add one, two, three or four values. For example:
/* adds 10 pixel margin all around the element */
margin: 10px;
/* adds 10 pixel to the top and bottom and 20 pixel to the left and right. */
margin: 10px 20px;
/* sets top to 10 pixel, left and right to 20 pixel, and bottom to 30 pixel */
margin: 10px 20px 30px;
/* sets top to 10 pixel, right to 20 pixel, bottom to 30 pixel, and left to 40 pixel */
margin: 10px 20px 30px 40px;
So, I mentioned that margin separates elements from each other. CSS does it in a very intuitive way.
Example for margin:
Let’s say we have this HTML code with two divs and a couple of paragraphs inside them:
<div class="first-div">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
<div class="second-div">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. </p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
Let’s add some styling to this:
body {
margin: 0;
padding: 0;
}
p { margin: 0; }
.first-div {
background-color: blue;
color: white;
}
.second-div {
background-color: orange;
color: white;
}
So, here we just reset the margin and padding properties on the body element, and I also reset the margin on the paragraph element since browsers add some margin to it by default.
If we add
margin: 40px;
to both div, it means we add 40 pixel space around those divs. Since divs are block-level elements and they appear one after the other we would assume that the space between the two divs would be 80px (40+40). But if you look at it in the browser, you can see that it is not the case.
Here, the browser will only use one width. if the margins are not the same, the larger of the two will be used. However, it’s worth to note that this functionality is not applied to elements that are inline or positioned absolutely.
Leave a reply
You must be logged in to post a comment.