Guy Lowe
Guy Lowe

Reputation: 2370

How to make a flexible 2x3 grid using flexbox

I'm trying to create a HTML page that has 3 rows of 2 cells in each. I want all 6 cells to fill the entire page equally without having to specify a height so that when the browser is re-sized, so to are the cells.

I am trying to use the following flex layout but I'm getting them all in a row.

.outer {
  display: flex;
  min-height: 100%;
}

.row {
  border: 1px solid blue;
  display: flex;
  flex: 1.0;
  flex-grow: 1.0;
}

.item {
  background-color: orange;
  flex: .5;
  flex-grow: 0.5;
  border: 1px solid red;
}
<div class="outer">
  <div class="row">
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <div class="row">
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

Upvotes: 1

Views: 7181

Answers (1)

kukkuz
kukkuz

Reputation: 42360

Make the outer wrapper a column flexbox:

  • add flex: 1 to each row so that the rows share the vertical space,

  • add flex: 1 to each item so that the columns share the horizontal space,

  • finished up with height: 100% on both body and html elements (you can also use viewport height to set the min-height) and setting default body margin to zero.

See demo below:

body, html {
  margin: 0;
  height: 100%;
}

.outer {
  display: flex;
  min-height: 100%;
  flex-direction: column; /* added */
}

.row {
  border: 1px solid blue;
  display: flex;
  flex: 1; /* added */
}

.item {
  background-color: orange;
  border: 1px solid red;
  flex: 1; /* added */
}
<div class="outer">
  <div class="row">
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <div class="row">
    <div class="item"></div>
    <div class="item"></div>
  </div>
  <div class="row">
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

Upvotes: 3

Related Questions