Home > Net >  How to create a flexbox grid with a column span and spacing between elements
How to create a flexbox grid with a column span and spacing between elements

Time:03-03

I am trying to create a flexbox grid which should look like that enter image description here

The basic grid layout is pretty easy to create, but I have a very hard time adding the spacing between the elements. As you can see in the code snippet, the spacing in the second line is not working properly.

#flexContainer {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 200px;
  width: 600px;
}

.rowContainer {
  display: flex;
  flex-direction: row;
  gap: 16px;
}

.thirdElement {
  flex-grow: 1;
  height: 40px;
  background-color: red;
}

.twoThirdsElement {
  flex-grow: 2;
  height: 40px;
  background-color: red;
}
<div id="flexContainer">
  <div >
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
</div>

CodePudding user response:

Use CSS grid

#flexContainer {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.rowContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
}

.thirdElement {
  height: 40px;
  background-color: red;
}

.twoThirdsElement {
  grid-column:span 2;
  height: 40px;
  background-color: red;
}
<div id="flexContainer">
  <div >
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
</div>

CodePudding user response:

This looks to me like a three column grid with the fourth item spanning two colums.

Here's a simplified version. Obviously you'll want to style the items as you need them.

#flexContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
  height: 200px;
  width: 600px;
}

#flexContainer>* {
  background-color: red;
}

.twoThirdsElement {
  grid-column: auto / span 2;
}
<div id="flexContainer">
  <div>
  </div>
  <div>
  </div>
  <div>
  </div>
  <div >
  </div>
  <div>
  </div>
</div>

CodePudding user response:

You not need to <div >. It fixes only with one flex property for #flexContainer.

#flexContainer {
  display: flex;
  flex-wrap: wrap;
  height: calc(80px   (600px / 20)); /* (600px/20) == 5% of 600px. result = 80px   5%(600px). it is for a gap between rows that is equal with gap: 5%; for columns.*/
  align-content: space-between;
  gap: 5%;
  width: 600px;
}

.thirdElement {
  flex-basis: 30%;
  height: 40px;
  background-color: red;
}

.twoThirdsElement {
  flex-basis: 65%;
  height: 40px;
  background-color: red;
}
<div id="flexContainer">
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
</div>

  • Related