How do make columns in a grid "space-evenly" like with flexbox?
Asked Answered
P

2

11

I have this grid CSS

.grid {
    display: grid;
    grid-column-gap: 50px;
    grid-template-columns: repeat(3, 1fr);
}

which is sitting in a div with width: 500px

but I noticed that the first item in the grid "hugs" the left edge of the div but the far most right item doesn't touch the edge of the div.

In flexbox I could achieve this with (near enough):

.flex {
    display: flex;
    justify-content: space-between;
 }

how do I do this responsively with the grid?

I know I can change the grid-column-gap but that seems flakey

Popedom answered 19/1, 2022 at 12:15 Comment(3)
you should try gapGametophyte
also justify-content: space-between; it does work with CSS gridSporocarp
CSS-Tricks: justify-contentTerpineol
S
15

Use auto instead of 1fr and the same justify-content will work like with flexbox:

.grid {
  display: grid;
  grid-column-gap: 50px;
  grid-template-columns: repeat(3, auto);
  justify-content:space-between;
}
<div class="grid">
  <div>aaa</div>
  <div>bbb</div>
  <div>ccc</div>
</div>
Sporocarp answered 19/1, 2022 at 12:23 Comment(2)
grid-template-columns: repeat(3, auto); can safely be replaced by grid-auto-flow: column; then, right?Stipe
@Stipe yes if you want only one row but not if you want more elements (more rows) and still keep 3 columnsSporocarp
S
4

Consider using auto-fit keyword to fit columns into the available row space by expanding them.

.grid-container {
  display: grid;
  grid-column-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}

.grid-item {
  background-color: blue;
  padding: 30px;
}
<div class="grid-container">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
</div>
Sixpack answered 19/1, 2022 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.