CSS grid where one column shrinks to fit content, the other fills the remaning space

You need to use grid-template-column and set the size of column you want to shrink-to-fit as auto, and specify the size of at least one other column using the fr unit.

Example:
To recreate the sidebar-content layout, where the sidebar is collapsible,

-------------------------------
| Sidebar |       Content     |
-------------------------------

you can create the grid as:

.grid {
  display: grid;
  ...
  grid-template-columns: auto minmax(0, 1fr); // see note below
  grid-template-areas: "sidebar content";
}
.sidebar {
  grid-area: sidebar;
}
.content {
  grid-area: content;
}

See the codepen here for a demo & code: https://codepen.io/khs/pen/vegPBL
You can click on the navbar to see auto-sizing in action.


Note: One thing I’ve learnt since writing this answer is that in most cases, and especially in a fixed-height/fixed-width layout, you should use minmax(0, 1fr) instead of 1fr. The reason is that 1fr is actually a shorthand for minmax(auto, 1fr). This breaks when used for fixed layouts with longer content. See this question for more details: Why does minmax(0, 1fr) work for long elements while 1fr doesn’t?
Hence I’ve updated my answer to reflect the fact. The minmax might be a little verbose, but it’s almost always what you want for this kind of layout.


Context: I bumped into this question recently while learning to use grid in my app. With some help from ilyaigpetrov’s answer, I was able to get a shrink-to-fit column sizing to work. Their answer doesn’t give much explanation though, so I thought I’d add this:

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)