Home > Blockchain >  grid-auto-flow:column with 1fr as width
grid-auto-flow:column with 1fr as width

Time:08-04

Is it possible to use 1fr as the column-width with grid-auto-flow: column?

grid-template-columns: repeat(4, 1fr)

So that the width of each column would be the same and defined by the widest column, but I can only achieve it by defining the number of columns:

Example for grid-template-columns: repeat(4, 1fr)

grid-auto-flow: column

I'm in need of grid-auto-flow: column because the amount of columns is variable, but I want to have them in the same width, without defining it in px:

Example for grid-auto-flow: column

CodePudding user response:

Grid has the auto-fill and auto-fit keywords, that can do this for you (if I'm fully understanding what you want, at least):

HTML

<div >
  <div>col1</div>
  <div>col2</div>
  <div>col3</div>
  <div>col4</div>
</div>

CSS

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  grid-auto-rows: auto;
  gap: 1rem;
}

.grid > div {
  background: red;
}

Results in https://codepen.io/isaactfa/pen/zYWWKQK.

I'll let Sara Soueidan explain the difference between auto-fill and auto-fit: https://css-tricks.com/auto-sizing-columns-css-grid-auto-fill-vs-auto-fit/.

CodePudding user response:

You are looking for grid-auto-columns: 1fr

.grid {
  display: grid;
  grid-auto-columns: 1fr;
  grid-auto-flow: column;
  gap: 5px;
  margin: 10px;
}

.grid>div {
  height: 50px;
  background: red;
}
<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>

  • Related