Cutup #2 Margin

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.

//example
margin-bottom: 10px;
margin-left: 20px;
margin-right: 30px;
margin-top: 40px;

② 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.

③ Shorthand

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

④ 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

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.

 

?Codepen

See the Pen Cutup #2 Margin: Margin collapsing by nana (@nana8) on CodePen.0


Thanks for reading,
please share it.
Related
UI: State styles of card component
UI: State styles of card component
ui
article
Case study: web design focused on interaction.
Case study: web design focused on interaction.
web
interaction
UX/UI
The story of editorial design for book ²/₂: The Art of Toy Story 4
The story of editorial design for book ²/₂: The Art of Toy Story 4
Print
Editorial