lucifer63 lucifer63 - 3 months ago 12
CSS Question

How to create a flexible adaptive table-like layout?

Don't know if this question is simple or no, but i got stuck with it: is it possible to create a flexible adaptive table-like layout which changes it's columns amount depending on a window width?

Illustration:
A visual example of the layout i talk about
(green border means initial size of a block (size of a block contents), black border means calculated/rendered size of a block)

The goal is to create a layout in which:


  1. Blocks are aligned like in a table - has the same space between them,

  2. The height of a row is the height of the block with the greatest height in this row,

  3. Columns amount are changing depending on a window width, for example there will be 1 column if the width is less than 300px, 2 column - 500px, 3 columns - 750px and 4 columns - >1000px



Actually, i already achieved this with JS and its not very hard for my PC to execute the script i wrote, so i think the script is optimized well, but anyway i hope that it can be done with pure CSS.

Btw, i can show my solution (CSS+JS), but i think it has no value.

Thanks in advance!

Answer

Flexbox and media queries can do this:

* {
  box-sizing: border-box;
}
.wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  width: 80%;
  margin: auto;
  border: 1px solid red;
  padding: 1em;
}
.box {
  border: 1px solid grey;
  margin-bottom: 1em;
  flex: 1 0 100%;
  background: #c0ffee;
  padding: 0 1em;
}
@media screen and (min-width: 500px) {
  .box {
    flex: 0 0 48%;
    background: #bada55;
  }
}
@media screen and (min-width: 750px) {
  .box {
    flex: 0 0 30%;
    background: rebeccapurple;
  }
}
@media screen and (min-width: 1000px) {
  .box {
    flex: 0 0 24%;
    background: #b19d09;
  }
}
<div class="wrapper">
  <div class="box">
    <p>Lorem ipsum dolor sit.</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eum, totam.</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eaque, cum. Voluptate natus quaerat eaque incidunt, accusamus veniam facere, alias provident odio est rerum commodi?</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Optio, dolore.</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit.</p>
  </div>
  <div class="box">
    <p>lorem</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus nobis odit possimus porro. Nihil, modi.</p>
  </div>
  <div class="box">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Praesentium vel, accusamus cupiditate esse quisquam, nisi hic dolores assumenda adipisci, illum ab itaque nemo placeat! Dolorum aliquam iure veritatis reprehenderit libero.</p>
  </div>
</div>

Codepen Demo

A Complete Guide to Flexbox @ CSS-Tricks.com

Comments