user10012
user10012

Reputation: 715

CSS Grid Specify First Column and set Fractional Unit For Unknown Remaining

I am trying to learn the CSS grid, but having trouble with what seems like it should be a basic repeat. Consider the following; I have 3 div elements in a header tag. I want the first div to be at least 450px and the remaining div elements (which could be 2, 3 or 4) to all be equal parts of the remaining space.

I assumed the following would work, but it seems it's not as straightforward as I thought. What am I missing?

header {
  display: grid;
  grid-template-columns: minmax(450px, 1fr) repeat(auto-fill, 1fr);
  grid-gap: 1rem;
}
<header>
  <div>
    <p>450px</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
</header>

Upvotes: 2

Views: 550

Answers (2)

Temani Afif
Temani Afif

Reputation: 272806

You need a column flow for this:

header {
  display: grid;
  grid-auto-flow:column; /* column flow */
  grid-template-columns: minmax(450px, 1fr); /* first column */
  grid-auto-columns:1fr; /* all remaining equal width */
  grid-gap: 1rem;
}
<header>
  <div>
    <p>450px</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
</header>

<header>
  <div>
    <p>450px</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
</header>

Upvotes: 2

Pete
Pete

Reputation: 58422

You can use auto-fit instead of auto-fill:

auto-fit

Behaves the same as auto-fill, except that after placing the grid items any empty repeated tracks are collapsed. An empty track is one with no in-flow grid items placed into or spanning across it. (This can result in all tracks being collapsed, if they’re all empty.)

header {
  display: grid;
  grid-template-columns: minmax(450px, 1fr) repeat(auto-fit, minmax(0, 1fr));
  grid-gap: 1rem;
}
<header>
  <div>
    <p>450px</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
</header>
<header>
  <div>
    <p>450px</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
  <div>
    <p>1fr</p>
  </div>
</header>

Upvotes: 2

Related Questions