Vingtoft
Vingtoft

Reputation: 14596

CSS grid | How to autofit columns of different sizes?

I'm trying to utilize CSS grid (for the first time), I'm struggling with some basic problems.

I'm building a footer with three components.

  #footer-content {
    position: relative;
    margin: 0 auto;
    padding: 0 20px;
    max-width: $max-width;
    width: 100%;
    height: 100%;
    color: white;

    display: grid;
    grid-template-columns: 12% 12% 76%;
}

For mobile:

@media only screen and (max-width: 800px) {
  #footer-content {
      grid-template-columns: 50% 50% 100%;
    }
}

The problem with above code: The third element (width 100%) is not pushed to next line but appears out of the screen.

Using grid-template-columns: repeat(auto-fit, 50% 50% 100%); does not work.

Using grid-template-columns: repeat(auto-fit, 50%); works: the third element is pushed down but is only 50% width instead of 100%.

Question: How can I use the CSS grid to auto-fit three columns of different sizes?

Upvotes: 2

Views: 5062

Answers (1)

Paulie_D
Paulie_D

Reputation: 114991

Grid-columns don't wrap so this grid-template-columns: 50% 50% 100%; makes no sense for two columns. You would define TWO columns and tell the third element to span them both on the following row.

.box {
  height: 150px;
  background: lightblue;
  border: 1px solid grey;
}

#footer-content {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-gap: .25em;
}

.box:nth-child(3) {
  grid-column: span 2;
}
<div id="footer-content">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Upvotes: 5

Related Questions