DEV Community

Masatoshi Nishiguchi
Masatoshi Nishiguchi

Posted on

CSS adding margin to all children

Sometime I want to add margin to all children in case that they get stacked on mobile devices. It would be nice if I have a utility CSS that does the job and can be applied to a parent element.

.children-mb-1 > * {
  margin-bottom: 0.25rem !important;
}
.children-mb-2 > * {
  margin-bottom: 0.5rem !important;
}
.children-mb-3 > * {
  margin-bottom: 1rem !important;
}
.children-mb-4 > * {
  margin-bottom: 1.5rem !important;
}
.children-mb-5 > * {
  margin-bottom: 3rem !important;
}
Enter fullscreen mode Exit fullscreen mode

I adopted values from Bootstrap because I like it.

That's it.

Top comments (3)

Collapse
 
nikolab profile image
Nikola Betica

Hi. I think you should drop !important rule. Like this, it will override any other margins on any child element and that is probably not what you want. Good idea though, cheers.

Collapse
 
mnishiguchi profile image
Masatoshi Nishiguchi

Hmm, I tried to understand what you meant but I couldn't. When I use this utility class, I want it to be applied on all child elements. Overriding is fine if there is.

Collapse
 
nikolab profile image
Nikola Betica

Ok, if that's what you need. It just seem to me you should override styles with selector specificity rather than important. Important should be used as a last case scenario or a quick fix, not a permanent solution.