22

I am testing CSS grid for my new responsive layout, but I am having a problem with wrapping.

I have a nav bar with a header that should be pushed to the left and 4 buttons that should be pushed to the right. The problem right now is that using:

grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))

Makes, as expected 5 evenly spaced and responsive grid cells. The problem is that I want the button cells to be significantly smaller than the header. So instead of it being 1fr 1fr 1fr 1fr 1fr, I want 8fr 1fr 1fr 1fr. How can I do this while still keeping the wrapping/responsive properties of using repeat autofit?

Codepen example illustrating the problem: https://codepen.io/johnpyp/pen/ZJxdYK

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

.grid>* {
  align-text: center;
  background-color: lightgreen;
  height: 200px;
}
<div class="grid">
  <div>I want this to be 8fr, but it is 1fr like the rest.</div>
  <div>1fr</div>
  <div>1fr</div>
  <div>1fr</div>
</div>

0

2 Answers 2

14

You can tell the first grid item to span 8 columns:

.grid > div:first-child {
  grid-column: span 8;
}

https://codepen.io/anon/pen/JyLQRB?editors=1100

Sign up to request clarification or add additional context in comments.

4 Comments

I'm confused now because that solution works with when minmax is set to 100px, 100px won't work responsively because it can't shrink down to 320px like on an iPhone, it is minimum 800px. To get around this, I tried to set minmax to 40px (320 / 8, so it could at least fit 8 columns on the screen at once) and the wrapping failed to work! Can you explain why this is happening? And maybe a solution? Example: codepen.io/johnpyp/pen/ZJxdYK
Interestingly, it doesn't if you specifically shrink the browser window, but after hosting the code on my website I can confirm it does work correctly on mobile! Thanks a lot.
Also, is it possible to set individual min widths for each of the elements?
I guess you can try sizing individual items by targeting them individually, the way I did for the first item.
2
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 8fr 1fr 1fr 1fr;
}

https://css-tricks.com/snippets/css/complete-guide-grid/#fr-unit

1 Comment

This doesn't work because the content doesn't wrap when it hits a minimum width.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.