Home > Mobile >  Center children in a grid that don't fit column
Center children in a grid that don't fit column

Time:04-06

I am using Tailwind and I have a grid layout and I want children that don't fit the column to be centered. I've tried justify-items-center and place-items-center but neither do anything.

e.g. In this example I want the bottom two to be centered.

CodePudding user response:

I will start by first replacing the grid with a flex instead because grid is not suited for alignment across an entire row. A detailed explanation can be found here.

With that said, this is my suggested solution using flex.

<script src="https://cdn.tailwindcss.com"></script>

<div >
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

There are some pretty interesting and creative ways to center uneven elements on the last row of a CSS grid. They all try to get around the fact that CSS grid isn't the right solution to the problem though.

You can read more about why here: Aligning grid items across the entire row/column (like flex items can)

The best approach would be to use flexbox instead.


Here's a rough demonstration: https://play.tailwindcss.com/37YqZZUE0o.

That may not be exactly the behaviour you had in mind but it can be tweaked as necessary to accomplish whatever you're going for.

  • Related