Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2x2 grid in Flexbox with fixed width column

Tags:

html

css

flexbox

Is it possible to create this grid with Flexbox:

----------
A1 | B1
----------
A2 | B2
----------

A1&A2 have a fixed width (50px) and B1&B2 fill the remaining space. I don't want to create wrappers for the columns, because I would like to reorder the cells on mobile.

like image 307
Michal Avatar asked Dec 04 '14 11:12

Michal


2 Answers

Simple 2X2 Flexbox grid — fixed and fluid

Compatibility: IE 11 + and all modern browsers. Safari is supported with the -webkit- prefix.

The stars of this show are:

  • The display: flex and flex-wrap: wrap properties for the container. The "wrap" value allows the contents of the container to break onto a new line as required.

  • The flex shorthand property:

    [The initial value of the flex property is] the concatenation of the initial values of its longhand properties:

    • flex-grow: 0
    • flex-shrink: 1
    • flex-basis: auto

    This is an easy guide to Flexbox over on CSS Tricks

In our example we use:

  • display: flex and flex-wrap: wrap on the container div

  • flex: 1 1 calc(100% - 50px) for the two re-sizeable divs. This tells the div to have a default width of 100% minus the 50px of the fixed cell. Technically it is allowed to grow and shrink, though as it is set as a percentage, it would re-size regardless.

  • flex: 0 0 50px for the fixed cells. This tells the div to have a default width of 50px and then not grow or shrink.

Complete Example

.flex-grid {
  display: flex;
  flex-wrap: wrap;
  height: 500px;
}
.grid-item {
  flex: 1 1 calc(100% - 50px);
  background: #F90;
  border-top: solid 1px #000;
}
.grid-item:nth-child(odd) {
  background: #F00;
  flex: 0 0 50px;
}
<div class="flex-grid">
  <div class="grid-item">
    A1
  </div>
  <div class="grid-item">
    B1
  </div>
  <div class="grid-item">
    A2
  </div>
  <div class="grid-item">
    B2
  </div>
</div>
like image 57
misterManSam Avatar answered Oct 12 '22 11:10

misterManSam


Use width: calc(100% - 50px) for the width of B1 and B2

FIDDLE

.container {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  width: 40%;
  height: 100px;
  max-height: 100px;
  border: 1px solid green;
}
.container div:nth-child(-n + 2) {
  background: yellow;
  width: 50px;
  height: 50px;
}
.container div:nth-child(n + 3) {
  background: aqua;
  height: 50px;
  width: calc(100% - 50px);
}
<div class="container">
  <div>A1</div>
  <div>A2</div>
  <div>B1 - Where B1&B2 fill the remaining space</div>
  <div>B2 - Where B1&B2 fill the remaining space</div>
</div>
like image 37
Danield Avatar answered Oct 12 '22 09:10

Danield