How to space the children of a div with css?

I want a gap of say 30px; between all children of my div. E.g if I have:

<div id="parent">    
   <img ... />
   <p>...</p>
   <div>.......</div>
</div>

I want all of them to have a space of 30px; between them. How can I do this with CSS?


Solution 1:

For an unknown amount of children you could use.

#parent > * {
    margin: 30px 0;
}

This will add a top and bottom margin of 30px to all direct children of #parent.

But img is not displaying as block default, so you may use:

#parent > * {
    display: block;
    margin: 30px 0;
}

Vertical margins of block elements will be collapsed. But you will have margins at top and bottom of your parent div. To avoid that use the following code:

#parent > * {
    display: block;
    margin-top: 30px;
}

#parent > *:first-child {
    margin-top: 0px;
}

This will only add top margin and removes that top margin for the first element.

Solution 2:

The following css will work well

div > *:not(:last-child) {
    display: block;
    margin-bottom: 30px; 
} 

> selects all elements that are direct children of the div (so you don't get weird inner spacing issues), and adds a bottom margin to all that aren't the last child, using :not(:last-child) (so you don't get a trailing space).

display: block makes sure all elements are displayed as blocks (occupying their own lines), which imgs aren't by default.

Solution 3:

Probably the easiest way is this:

#parent * {
  margin-bottom: 30px;
}

or

#parent * {
  margin: 15px 0;
}

Keep in mind, though, that this will get everything in #parent, including things inside the p and div tags. If you want just the direct children, you can use #parent > * (this is call the direct descendent selector) instead.

Keep in mind, <img> is an inline element by default, so you might need to do:

#parent img {
  display: block;
}

for it to use the margins.

Solution 4:

You can easily do that with:

#parent > * + * {
  margin-top: 30px;
}

This will be applied to all direct children except the first one, so you can think of it as a gap between elements.