Search code examples
javascripthtmlcsscss-grid

CSS Grid: Fit grid columns to the widest column


const items = Array.from(column.children)

const widths = items.map(item => item.offsetWidth)

const widest = widths.reduce((widest, current) => widest > current ? widest : current, 0)

items.map(item => item.style.width = `${widest}px`)
body {
  margin: 0;
}

body * {
  font-family: Helvetica;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: grid;
}

#column {
  grid-auto-columns: max-content;
  grid-auto-flow: column;
}

li {
  text-align: center;
  padding: 10px 10px;
  color: lightcyan;
  background: lightseagreen;
  border-right: 2px solid lightcyan;
}
<ul id="column">
  <li>S</li>
  <li>Med</li>
  <li>Widest Item</li>
</ul>

I'm making the list items fit the largest item in the list with a little bit of javascript. How may I accomplish this using CSS only?

This can also be looked at from the perspective of rows in the grid.


Solution

  • Set the UL's display to inline-block. For horizontal you can mix (flex, inline-flex) with css-grid, make a wrapper div with type flex or inline-flex.

    body {
      margin: 0;
      font-family: Helvetica;
    }
    
    div {
      display: inline-flex;
    }
    
    ul {
      margin: 0;
      padding: 0;
      list-style: none;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
    }
    
    li {
      text-align: center;
      padding: 10px 10px;
      color: lightcyan;
      background: lightseagreen;
      border-right: 2px solid lightcyan;
    }
    <div>
      <ul id="column">
        <li>S</li>
        <li>Med</li>
        <li>Widest Item</li>
      </ul>
    </div>