skip to Main Content

How can I achieve the "space-between" effect of Flexbox with CSS Grid?

You can see my code in the following link:

Codepen – Flexbox and Css Grid

.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  border: 1px solid black;
  justify-items: center;
}

.flex-container {
  display: flex;
  justify-content: space-between;
  border: 1px solid black;
}

.box {
  margin: 10px;
  border: 1px solid red;
  width: 120px;
  height: 120px;
  background-color: lightcyan;
  text-align: center;
  line-height: 120px;
}
<h1>Css Grid</h1>
<section class="grid-container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
</section>
<h1>Flexbox</h1>
<section class="flex-container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
</section>

I have explained myself wrong, what I want to achieve is the second image using css grid

enter image description here

Thanks

2

Answers


  1. Just change this property in your flex container:
    justify-content: space-between; to this: justify-content: space-around;
    They are quite self descriptive. I think it doesn’t need extra information.

    An easy way to play around with this is using a browser inspector tool.

    Login or Signup to reply.
  2. Just set margin:10px auto; on .flex-container .box.

    After if you want to create a 3 columns, grid you will need to add extra CSS as in below demo:

    .flex-container {
      display: flex;
      flex-wrap: wrap; /***** ADDED *****/
      border: 1px solid black;
    }
    
    .flex-container .box{ /***** ADDED *****/
      margin:10px calc(16.5% - 60px);
      flex-grow: 1;
      max-width:120px;
    }
    

    DEMO

    .grid-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      border: 1px solid black;
      justify-items: center;
    }
    
    .flex-container {
      display: flex;
      flex-wrap: wrap;
      /*justify-content: space-between;*/
      border: 1px solid black;
    }
    
    .flex-container .box{ /***** ADDED *****/
      margin:10px calc(16.5% - 60px);
      flex-grow: 1;
      max-width:120px;
    }
    
    .box{
      margin:10px;
      border: 1px solid red;
      width:120px;
      height:120px;
      background-color: lightcyan;
      text-align: center;
      line-height:120px;
    }
    <h1>Css Grid</h1>
    <section class="grid-container">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
      <div class="box">Box 3</div>
      <div class="box">Box 4</div>
    </section>
    <h1>Flexbox</h1>
    <section class="flex-container">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
      <div class="box">Box 3</div>
      <div class="box">Box 4</div>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search