GUF
GUF

Reputation: 21

CSS Grid: How to have an item that span across all columns and auto-fit the others across the remaining space

I would like to have a title spanning across the full-width and on row below have columns that fit the full-width as well.

In the following example, I was expecting the FOO and BAR to take the full width of the screen (50% each), but as soon as the viewport is exceeding 300px, the grid creates empty columns.

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));">
  <h1 style="grid-column: 1 / -1; border: 1px solid black;">TITLE</h1>
  <div style="background-color: red;">FOO</div>
  <div style="background-color: green;">BAR</div>
</div>

Here is the result:

result

And here is what I was expecting

expected

Do you know why the auto-fit property isn't working ?

Upvotes: 1

Views: 1046

Answers (2)

GUF
GUF

Reputation: 21

I included titles in the grid because I want all div to be the same size. In the example below, I want the div under TITLE 1 to be the same width than the div under TITLE2:

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(125px, 1fr));">
    <h2 style="grid-column: 1 / -1; border: 1px solid black;">TITLE 1</h2>
    <div style="background-color: red;">FOO</div>
    <div style="background-color: green;">BAR</div>
    
    <h2 style="grid-column: 1 / -1; border: 1px solid black;">TITLE 2</h2>
    <div style="background-color: red;">FOO</div>
</div>

Upvotes: 1

Shubham Srivastava
Shubham Srivastava

Reputation: 1877

The grid-column: 1 / -1; is breaking the css

Only put elements that will be auto placed inside repeat block

<h1 style="width : 100%; border: 1px solid black;">TITLE</h1>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));">
  <div style="background-color: red;">FOO</div>
  <div style="background-color: green;">BAR</div>
</div>

Upvotes: 1

Related Questions