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.
Margin can set all individual values.
//example margin-bottom: 10px; margin-left: 20px; margin-right: 30px; margin-top: 40px;
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
top 10px right 20px bottom 30px left 40px //in a clockwise direction
The margins in the second element are specified to
top 10px right, left 20px bottom 30px
The margins of the third element are specified to
top, bottom 10px right, left 20px
The last ones apply to
all sides 10px
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
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.
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.
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.
Like the parent and child case above, if there is no space in the empty element, the bigger margin is chosen between top margin and bottom margin of empty elements.
Please check my code in the CodePen below.
See the Pen Cutup #2 Margin: Margin collapsing by nana (@nana8) on CodePen.0
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.