Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSS grid to make multiple different-width columns wrap?

Tags:

html

css

css-grid

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>
like image 609
johnpyp Avatar asked Aug 21 '17 14:08

johnpyp


People also ask

How do you create a grid with 4 columns of equal width?

If you really need the columns to be the exact same width you should use: grid-template-columns: repeat(3, minmax(0, 1fr)); minmax(0, 1fr) allows the grid tracks to be as small as 0 but as large as 1fr , creating columns that will stay equal.

How do I use grid-template-columns to repeat?

grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); This way, we get a repeating number of columns (thanks to repeat() ) that will fill all of the available space of the grid (thanks to auto-fit ) while never shrinking narrower than 250px and each taking up an equal fraction of space (thanks to minmax() ).

How do you change the grid width of a column in CSS?

Set the following on the grid container: grid-template-columns: auto 1fr; This sets the width of the first column to equal the width of the widest item in that column, and the width of the second column to get the remaining width of the grid.


1 Answers

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

like image 182
Michael Benjamin Avatar answered Oct 29 '22 03:10

Michael Benjamin