CSS Grid - Can't align columns when using grid-column-start and grid-column-end

Viewed 768

I'm fairly new to CSS Grid and Flexbox so I would like your opinion on the best way to start with a 12 grid layout design that look likes these samples I found:

enter image description here

  1. When using CSS Grid and I try to plot out the structure I'm having an issue aligning the columns of multiple grid containers when using grid-column-start and grid-column-end to make a column span wider (bottom container): enter image description here

    CodePen using tailwindcss

  2. Am I doing something fundamentally wrong? Is flexbox better for this?

A tailwindcss solution is preferred but basic CSS is fine.

3 Answers

Your issue stems from the use of grid-flow-col. You're changing the way the grid is filled out. You've set 12 columns however by using grid auto flow column, it'll keep adding more as it needs to.

That becomes an issue on your second grid because while you have 12 defined columns and 12 elements, the first element is set to occupy 3 columns.

Remove '.grid-flow-col'.

Also, keep in mind that this: 'col-start-1 col-end-4' can be simplified to 'col-span-3'.

https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow

Browsers have some great built in developer tools for dealing with CSS grid. You can switch a grid overlay on which will show you exactly how things are going wrong.

You have to replace <div class="bg-black col-start-1 col-end-4"></div> for : <div class="bg-black col-start-1 col-end-2"></div>

Instead of having two parents <div>, you can group the two grids into a single parent <div> container.

Instead of having two individual <div> containers grouping each column, have a single <div> parent container to group both of the grids together. Then what you need to do is add additional row to a single parent grid:


<div class="container border-8 border-red-400 gap-4 grid mx-auto grid-cols-12 grid-rows-2 text-orange h-80 my-5">
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  
  <div class="bg-black col-start-1 col-end-4 row-start-2"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
  <div class="bg-black"></div>
  <div class="bg-red-700"></div>
</div>

Notice that there's few additional tailwind classes added: grid-rows-2 and also removed grid-flow-col class (I've also added a red border to make visual width comparison easier).

This will give this result:

enter image description here

Related