DEV Community

Discussion on: The case for * { margin: 20px }

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

You bring this up as an example of what one would be inclined to do as a first pass:

.post,
.post h1,
.post .sub-heading,
.post .body {
  margin: 20px;
}

.post .sub-heading {
  margin: -10px 20px 20px 20px;
}

This is a bad design to begin with. And I'd argue that your solution isn't much better:

& > * {
  margin: 20px;
}

You'll inevitably run into the problem of collapsing margins with both top and bottom set to 20px.

Better solution: Use unidirectional margins, consistently applying a margin to either the top or bottom of all elements (but not both). I prefer bottom margins. This means my spacing flows consistently from the top down.

Collapse
 
gajus profile image
Gajus Kuizinas

Use negative margin as is illustrated in one of the examples.

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Why introduce unnecessary complexity, though? You could just as well do 0 20px 20px 0 and have unidirectional flow, or margin-bottom: 20px, or only margin-top: 20px. You're creating problems for yourself that could be avoided altogether.

Thread Thread
 
gajus profile image
Gajus Kuizinas

Because it is not a real world scenario. The whole point of this pattern is to enforce a consistent spacing between members of a container. If one element requires different spacing than others, then your hierarchy of elements is off. I will update article to make this more clear.