xxjjnn
xxjjnn

Reputation: 15239

CSS Flex columns layout with overflow

Using pure CSS, is it possible to make the data flow in columns (like flex-direction: column) and also overflow the entire column layout? Like here:

scaling of columns

Examples seem to focus on specifying the number of columns upfront, or, using media queries to achieve this - but with the caveat that it hinges on page width and not on the size of the content (so you have to set the content to be e.g. 33% width when 3 columns).

Upvotes: 0

Views: 90

Answers (1)

Temani Afif
Temani Afif

Reputation: 272648

I think your best option is columns

.container {
  background:lightblue;
  padding:10px;
  column-count:3;
  column-gap:10px;
}
@media (max-width:800px) {
  .container {column-count:2}
}
@media (max-width:400px) {
  .container {column-count:1}
}

.container div {
  padding:10px;
  margin:5px 0;
  display:inline-block;
  width:100%;
  box-sizing:border-box;
  background:grey;
}


/* irrelevant CSS*/
.container {
  counter-reset:num;
}
.container div:before {
  content:counter(num);
  counter-increment:num;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Like below if you want to control the width:

.container {
  background:lightblue;
  padding:10px;
  column-width:max(200px,100vw/4);
  column-gap:10px;
}


.container div {
  padding:10px;
  margin:5px 0;
  display:inline-block;
  width:100%;
  box-sizing:border-box;
  background:grey;
}


/* irrelevant CSS*/
.container {
  counter-reset:num;
}
.container div:before {
  content:counter(num);
  counter-increment:num;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

The max(200px,100vw/4) will get you a maximum number of columns equal to 3 and the 200px will control when we fall to 2 columns then 1.

Upvotes: 1

Related Questions