Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make space between elements inside div container

Tags:

html

css

flexbox

I have a flex-container which will be dynamically filled by elements. Container doesn't have fixed width (I use max-width: max-content;) and can contain as many element as I want. The problem is that I need spacing between these elements, but don't need spacing on the left and right side between an element and the container.

Of course I can do it with .element{margin-right: 10px} and .element:last-child{margin-right: none;}, but is there a way to achieve it without pseudo-classes and JS?

<div class="container">
  <div class="element">my element</div>
  <div class="element">my element</div>
  ...
  <!-- nubmer of elements changing -->
  ...
</div>
like image 445
Yas'ka Avatar asked Dec 10 '22 03:12

Yas'ka


1 Answers

You can use flex with the column-gap property.

Also, setting justify-content: space-between will ensure an even space between elements if the width of the parent container increases.

.container {
  display: flex;
  column-gap: 20px;
  justify-content: space-between;
}

.element {
  background: yellow;
}
<div class="container">
  <div class="element">my element</div>
  <div class="element">my element</div>
  <div class="element">my element</div>
  <div class="element">my element</div>
  <div class="element">my element</div>
  <div class="element">my element</div>
  <div class="element">my element</div>
</div>
like image 101
Creaforge Avatar answered Dec 12 '22 16:12

Creaforge