How can I make a Tailwind column full-width when it is the only column in a row

Viewed 615

I have a grid that spans 2 columns per row.

const items = [1,2,3,4,5,6]

...

<ul className="grid grid-cols-2 gap-8 mt-16 justify-items-center">
{
    items.map(item =>
        <li className="text-center max-w-sm" key={item.name}>
        {item.name}
        </li>
    )
}
</ul>

With 6 items, the grid aligns perfectly, with 2 items per row. But if I add an additional item, the new item is added to a new row but is restricted to a single column.

I'm trying to figure out a way to have an item on it's own row span across both columns. Is this possible with tailwind/css, or would it require additional JS to calculate if a row should span.

1 Answers

I can't think of an automatic way for grid classes to handle this case, but a JavaScript solution is below. It essentially checks to see if last array element is in an odd length list and adds a col-span-2.

items.map((item, i) => {
  const spanClass = (i === items.length - 1) && (items.length % 2) ? 'col-span-2' : '';
  return (
    <li className=`${spanClass} text-center max-w-sm` key={item.name}>
      {item.name}
    </li>
  )
})
Related