Home > Enterprise >  Layout gap/margin center two last elements with flex-wrap
Layout gap/margin center two last elements with flex-wrap

Time:08-09

I have issues with a layout where I want to center the last two elements on a row. First I tried with grid and couldn't find any proper solution so I found a way to solve it with "flex-wrap" and it looks pretty good.

The issue I'm facing now is with the gap/margin. I can't find any good solution while I'm setting the width to 33,33%.

Is there any other good way to solve this? I'm kind of stuck and have been looking at this for hours now :) (see layout attached image)

#container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  flex-direction: column;
}

@media only screen and (min-width: 640px) {
  #container {
   display: flex;
   flex-wrap: wrap;
   justify-content: center;
   flex-direction: row
  }
}

.item {
  width: 100%;
  background: teal;
  color: white;
  border-radius: 10px;
  text-align: center;
 }
 
 @media only screen and (min-width: 640px) {
  .item {
    width: 33.33%;
  }
}
<div id="container">
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
</div>;

enter image description here

CodePudding user response:

You can use the gap parameter, see the example below.

Update:

Solution 1 Stretched Last element

#container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.item {
  width: 100%;
  background: teal;
  color: white;
  border-radius: 10px;
  text-align: center;
 }

/* Start Media Query*/

@media only screen and (min-width: 640px) {
  #container {
   display: flex;
   justify-content: center;
   flex-direction: row;
  }

  .item {
    flex: 1 1 30%;
  }
  
} /* End Media Query*/
<div id="container">
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
</div>

Solution 2 Not stretched last element

#container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.item {
  width: 100%;
  background: teal;
  color: white;
  border-radius: 10px;
  text-align: center;
 }

/* Start Media Query*/

@media only screen and (min-width: 640px) {
  #container {
   display: flex;
   justify-content: center;
   flex-direction: row;
  }

  .item {
    flex: 0 0 calc(33.33% - 15px);
  }
  
} /* End Media Query*/
<div id="container">

  <div >
    <p>Item</p>
  </div>
  
  <div >
    <p>Item</p>
  </div>
  <div >
    <p>Item</p>
  </div>
  
  <div >
    <p>Item</p>
  </div>
  
  <div >
    <p>Item</p>
  </div>
  
</div>

  • Related