Lobo de Colorado
Lobo de Colorado

Reputation: 307

CSS Grid: % and auto not working for Grid-Template-Rows

Here is my code:

.container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
    grid-template-rows: 20% 20% 20% 20% 20%;
    grid-column-gap: 40px;
    grid-row-gap: 10px;
}

fr = 1 fraction part of the screen (in case someone didn't know)

When I put a specific size for the rows, i.e 200px, it works! However, anything responsive i.e 20%, it's not running right.

Why not?

Any help appreciated.

Upvotes: 12

Views: 19798

Answers (2)

spygi
spygi

Reputation: 442

From MDN:

If the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto.

And expanding on Edmond's answer: you can fix this by giving your .container a fixed height (with px, % or whatever).

Note: using frs would still work even without specifying the height of the .container.

Upvotes: 8

Edmond Weiss
Edmond Weiss

Reputation: 541

The height and width of a container can only ever reach the max height and max width of its parent container when using relative units such as %, fr, and etc. Without looking at the rest of your HTML and CSS, I suspect you're misunderstanding/forgetting that point about parent-child relationships in CSS. If you want, each row to take up 20% height of the screen size, then your container's height must be 100% of the screen. You have to check the height of your container. You can test this by setting your container's height to 100%. If that doesn't take up 100% size of the screen then the parent of your container is not 100% height of the screen. Here is some code to make sure grid-template-rows property works as you intend:

html {
 height: 100%; // The height of your html document takes 100% size of window
}

body {
 height: 100%; // Body takes 100% height of html which is 100% height of window
}

.container {
  height: 100%; // Container takes 100% height of body which is 100% height of html which is 100% of window
}

Upvotes: 5

Related Questions