DEV Community

Cover image for CSS class to add margin for all child elements
Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

CSS class to add margin for all child elements

<div class="container space-kids">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  border: 2px solid white;
  padding: 12px;
  display: flex;
  width: 400px;
  .box {
    height: 50px;
    width: 50px;
  }
}

.space-kids {
  & > * {
    margin-right: 12px;
    &:last-child {
      margin-right: 0px;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Codepen

Update: css property gap works too. Thanks @afif for pointing it out. But other styles would work with universal selector


Thanks for reading πŸ’™

Follow @codedrops.tech for more.

Instagram ● Twitter ● Facebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech


Projects
Note Box - A chrome extension to add notes/todos based on URL

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (4)

Collapse
 
afif profile image
Temani Afif

you can use gap to do this: developer.mozilla.org/en-US/docs/W...

Collapse
 
ml318097 profile image
Mehul Lakhanpal

Thanks for pointing it out. But to add any other styles the universal selector would be better I guess. Anyways I'll just update the post.

Collapse
 
afif profile image
Temani Afif

You no more need any selector, a simple gap:12px applied to the flexbox container will do the job.

Thread Thread
 
ml318097 profile image
Mehul Lakhanpal

Yes I know. Its works the same way with css grids. I am saying if you need to apply styles other than that wont work.