How to space the children of a div with css?

Viewed 128532

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?

9 Answers

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.

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.

Use CSS gap property.

.parent_class_name{
  gap: 30px;
}

The above CSS code will apply a gap/separation of 30px between children of the parent_class_name class.

Example: This code will apply 1rem gap between element (rows and columns).

<div class="gap_container">
  <div>a</div>
  <div>b</div>
  <div>c</div>
</div>
.gap_container{
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

The gap property defines the size of the gap between the rows and columns. It is a shorthand for the following properties:

  • row-gap
  • column-gap

Apply row and column values separately. gap: row-value column-value;

Learn more: w3school

Related