Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Grid generating more columns than existing

I have a grid that for large screens (@media (min-width: 800px)) uses a grid of 12 columns with the next directive:

grid-template-columns: repeat(12, [col-start] 1fr);

But for mobile devices I use instead:

grid-template-columns: repeat(4, [col-start] 1fr);

Until here everything is fine, no clear problem. But if I add grid-gap: 1rem; the problem becomes obvious for the small screens since it seems that even though I specified 4 columns, it takes it as 12 columns 4 of them with 25% width and the rest with 0px so there is a bad behaviour of css.

I cannot reproduce it in a JSFiddle by the moment but I have some image of the problem.

For 12 columns on big screen:

Grid for 12 columns Computed values for 12 columns

Applied styles: (Other computed values)

 @media (min-width: 800px) {
   .my-grid {
     display: grid;
     padding: 2.5rem 4.875rem 0 4.875rem;
     grid-template-columns: repeat(12,[col-start] 1fr);
   }
 }

For 4 columns: Not good 4 columns computed values

Applied styles: (Other computed values)

   .my-grid {
     display: grid;
     grid-template-columns: repeat(4,[col-start] 1fr);
     padding: 1rem;
   }

As you can see the computed values for the 4 columns grid has 4 columns set and the rest with 0px width...

In the element inspection there are only the lines I wrote above.

Any idea of why do we have this behaviour?

On an additional note, I am using styled-components and it is a div.

Codepen with the error

like image 824
SirPeople Avatar asked Nov 21 '18 08:11

SirPeople


1 Answers

The element that is underneath had an span of:

grid-column: 1 / span 12;

This was forcing the CSS Grid to have 12 columns.

If we delete that element underneath, the CSS Grid behaves normally

like image 113
SirPeople Avatar answered Sep 28 '22 14:09

SirPeople