1

I'm building a grid layout using CSS Grid and I want all my columns to have the same size (fixed sized) and that size being the one of the largest column. I know that I can do it using JS or even display: table but I would like to do it using CSS Grid (if it's possible).

Here's what I have:

* {
  box-sizing: border-box;
}

div {
  display: grid;
  grid-template-columns: repeat(auto-fit, 120px);
  gap: 5px;
}

span {
  padding: 10px;
  border: 1px solid black;
}
<div>
  <span>Orange</span>
  <span>Purple</span>
  <span>Aquamarine</span>
  <span>Black</span>
  <span>Brown</span>
  <span>Red</span>
</div>

I fixed the width at 120px but I want that width to be the one of Aquamarine which is the largest one.

PepeW
  • 477
  • 1
  • 8
  • 24

1 Answers1

0

If you have a fixed number of columns, you can do it by placing your grid element inside a wrapper element styled with display: inline-block; and then setting grid-template-columns: repeat(6, 1fr);. See this answer.

However, I don't know how to do this in a grid where you have a variable number of columns by using auto-fit or auto-fill.

* {
  box-sizing: border-box;
}

.wrapper {
  display: inline-block;
}

.grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 5px;
}

span {
  padding: 10px;
  border: 1px solid black;
}
<div class="wrapper">
<div class="grid">
  <span>Orange</span>
  <span>Purple</span>
  <span>Aquamarine</span>
  <span>Black</span>
  <span>Brown</span>
  <span>Red</span>
</div>
</div>
Brett Donald
  • 6,745
  • 4
  • 23
  • 51