This is a question about the difference between margin and padding when styling the list.

Asked 2 years ago, Updated 2 years ago, 123 views

He styled the list elements in css around 6 minutes and 10 seconds of lecture 2-8 and compared margin and padding alternately. But what I'm curious about is that both of them gave 10px values up and down, but the actual style results were different.

li {
    padding: 10px 0;
}

When fed like this, the interval between each list is properly 10+10 which is 20px

li {
    margin: 10px 0;
}

When I used margin like this, the gap between each list was not 20px, but 10px overlapped, so it came out.

I think the interval between the lists should be 20px because both of them were given 10px up and down, but why did the margin get 10px? I'm curious.

fast-frontend css margin padding

2022-09-22 19:04

1 Answers

Hello, I'm Yamoo. :-D

Good question. It's very important!

This phenomenon is called Margin Collapping. In other words, the phenomenon of folding the margin space. This happens only in the up/down direction. This is not the case in the left/right direction. And It only occurs at the margin. Padding does not occur.

Let's understand it by drawing :)

margin collapsing

The figure on the left shows the CSS margin settings that the user expected.

We expected 50px of space, but the screen processed by the actual browser will have 30px of space, as shown in the picture on the right. Because it's bigger than 30 > 20, it looks like 30. If the margin setting in the box below is margin-top: 40px, the space will be 40. (40 > 30)

Note that margin calling occurs only between block elements. It is recommended that up/bottom margins are only given in one direction for this phenomenon.


2022-09-22 19:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.