How to make space between items using d-flex

Viewed 16946

I still do not know where I should separate my items by grid system and col and when to use d-flex? Imagine I have 4 buttons:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex justify-content-center">
  <button class="btn">First</button>
  <button class="btn">second</button>
  <button class="btn">Third</button>
  <button class="btn">fourth</button>
  <button class="btn">Fifth</button>
  <button class="btn">six</button>
</div>

I have items in row and center but without padding out space among them, how can I achieve it? And should I use col and row or flex?

myproblem

3 Answers

Instead of using justify-content: center, have a look at its other values:

justify-content: space-around, justify-content: space-evenly, justify-content: space-between.

They provide spacing between elements and should help.

In Bootstrap 5, There is an option to use gap. Using the gap you can provide space between flex items. I was also struggling with the same issue and i don't wanted to use margin or padding. So gap is the best solution for me.

.d-flex{
  gap:20px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex justify-content-center">
  <button class="btn">First</button>
  <button class="btn">second</button>
  <button class="btn">Third</button>
  <button class="btn">fourth</button>
  <button class="btn">Fifth</button>
  <button class="btn">six</button>
</div>

.d-flex {
width: 100%;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="d-flex justify-content-between" >
<button class="btn">First</button>
<button class="btn">second</button>
<button class="btn">Third</button>
<button class="btn">fourth</button>
<button class="btn">Fifth</button>
 <button class="btn">six</button>
</div>

<br>
OR
<br>


<div class="d-flex justify-content-around" >
<button class="btn">First</button>
<button class="btn">second</button>
<button class="btn">Third</button>
<button class="btn">fourth</button>
<button class="btn">Fifth</button>
 <button class="btn">six</button>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

If you are using bootstrap you need to add class.

Related