How to set the maximum width of a column in CSS Grid Layout?
"The fit-content function accepts one param, the maximum value. A grid column/row with this property set will still take up as little space as necessary, according to its content, but no more than the maximum value."
See this article: Becoming a CSS Grid Ninja!
You can solve your case while still making use of percentage-based maximums:
div {
outline: 1px dotted gray;
}
.container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: 1fr fit-content(20%);
}
.container div {
overflow: hidden; /* this needs to be set so that width respects fit-content */
}
<div class="container">
<div>
some content
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus eu leo ac ultrices. Vivamus ornare, orci sed pretium sollicitudin
</div>
</div>
<div class="container">
<div>
some content
</div>
<div></div>
</div>
You've misunderstood minmax
function. It first tries to apply maximum value and when that's not possible, it applies minimum.
So to fix your layout, you just need to calculate 20%
of your container width, apply it using max-width
property for you grid item, and use auto
in your grid-template-columns
property definition for the second column. Demo:
div {
outline: 1px dotted gray;
}
.container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: 1fr auto;
}
.container > :nth-child(2) {
max-width: 60px; /* 20% x 300px */
}
<div class="container">
<div>
some content
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec cursus eu leo ac ultrices. Vivamus ornare, orci sed pretium sollicitudin
</div>
</div>
<div class="container">
<div>
some content
</div>
<div></div>
</div>
Update: More flexible solution will be to use fit-content
function from this answer.