Today, I would like to share with you about Margin.
Margin, one of the properties in CSS, is an area of all four sides of an element.
① Individual margin
Margin can set all individual values.
② Margin vs Padding
Margin is an extra space outside of an element; pink area.
On the other hand, padding is an extra space within an element; yellow area.
Also, Margin doesn’t have background colour. Because it is an invisible area, a space between two elements. So if you want to give a background colour between two elements, you should replace margin to padding like below.
- The margins of the first element in the example above are specified to
left 40px //in a clockwise direction
- The margins in the second element are specified to
right, left 20px
- The margins of the third element are specified to
top, bottom 10px
right, left 20px
- The last ones apply to
all sides 10px
④ Horizontal centering
To center something horizontally in modern browsers, you can use
display: flex;justify-content: center;
However, in older browsers like IE8–9 that do not support Flexible Box Layout, these are not available. In order to center an element inside its parent, use:
margin: 0 auto;
width: ___ px; // must have width value
⑤ Margin collapsing
The top and bottom margins of two elements in the vertical direction are sometimes collapsed into a single margin that is equal to the bigger of the two margins. this does not apply to the horizontal direction.
There are three cases it will happen.
- Adjacent siblings
When there are two margins of adjacent elements vertically, these two margins are collapsed and the bigger margin value will be chosen, like the above image.
- Parent and first/last child
If there is no space in the parent element, such as border, padding or any context, the bigger margin is chosen between parent’s top margin and child’s top margin.
*Note: styles rather than spacing properties (e.g., colour, font-family etc) will still collapse.
- Empty blocks
🎈 That’t all for now
💌 Any questions or feedback
I would love to hear your feedback on how I can make it better for you. Please leave your comments below or through my Twitter.