Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap four columns into two rows of two columns with flexbox?

Tags:

html

css

flexbox

We are using flexbox and attempting to the following below. The goal is to have one column per item on mobile breakpoints, two columns on tablet breakpoints, and four columns on desktop breakpoints.

The example uses just four items, but let's say i had 5 or 6 items, then i just wanted the items to be responsive. If the row only has enough space to display 2 items per row, then i would expect each item to continue to move below the row above it.

How can this be achieved?

.flex-row {
  display: flex;
  @media screen and (min-width: 768px) {
    flex: 1;
    flex-direction: row;
    justify-content: space-between;
  }
}

.flex-col {
  margin: 6px;
  padding: 16px;
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  flex-direction: column;
  color: white;
}
 <div class="flex-row">
    <div class="flex-col">Assertively negotiate interoperable portals without cross functional process improvements. Dramatically incentivize tactical best practices with.</div>
    <div class="flex-col">Seamlessly grow competitive.</div>
    <div class="flex-col">Distinctively optimize user-centric mindshare vis-a-vis plug-and-play infomediaries. Seamlessly optimize impactful solutions and enabled infrastructures.</div>
    <div class="flex-col">Dynamically extend flexible catalysts for change via pandemic supply chains. Efficiently.</div>
    </div>

Current results

current

Expected results on tablet

expected

like image 746
usernameabc Avatar asked Feb 23 '18 20:02

usernameabc


1 Answers

Simply add flex-wrap:wrap to allow element to go to the next line if there is no enough space and consider media query if you want to control when the break will happen:

.flex-row {
  display: flex;
  flex: 1;
  flex-direction: row;
  flex-wrap: wrap;
}

.flex-col {
  margin: 6px;
  padding: 16px;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  flex-direction: column;
  color: white;
  box-sizing:border-box;
}

@media (max-width:767px) {
  .flex-col {
    flex-basis: calc(50% - 12px);
  }
}

@media (max-width:460px) {
  .flex-col {
    flex-basis: 100%;
  }
}
<div class="flex-row">
  <div class="flex-col">Assertively negotiate interoperable portals without cross functional process improvements. Dramatically incentivize tactical best practices with.</div>
  <div class="flex-col">Seamlessly grow competitive.</div>
  <div class="flex-col">Distinctively optimize user-centric mindshare vis-a-vis plug-and-play infomediaries. Seamlessly optimize impactful solutions and enabled infrastructures.</div>
  <div class="flex-col">Dynamically extend flexible catalysts for change via pandemic supply chains. Efficiently.</div>
</div>
like image 59
Temani Afif Avatar answered Nov 14 '22 21:11

Temani Afif