I'd like to create a web page layouts with flexible columns that may be bounded to certain maximum widths. For example a sidebar menu that takes 30% of the available horizontal space but shouldn't grow wider than 200px.
With CSS flexbox, I would go with a solution like this:
.flexbox-layout {
display: flex;
}
.flexbox-sidebar {
flex: 1 1 30%;
max-width: 200px;
background-color: lightblue;
}
.flexbox-content {
flex: 1 1 70%;
background-color: lightgreen;
}
<p>Layout based on CSS flexbox:</p>
<div class="flexbox-layout">
<div class="flexbox-sidebar">
<ol>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Menu item 3</li>
</ol>
</div>
<div class="flexbox-content">
<p>Content</p>
</div>
</div>
This is obviously a minimal example - the real layouts would be far more complex and I want to take advantage of CSS grid features like column/row spanning and auto columns, combined with media queries for responsiveness. Until now, I didn't manage to achieve the same effect of the above flexbox sample with CSS grid:
.grid-layout {
display: grid;
grid-template-columns: 30% 70%; /* Max. width for 1st column? */
grid-template-rows: auto;
}
.grid-sidebar {
background-color: lightblue;
}
.grid-content {
background-color: lightgreen;
}
<p>Layout based on CSS grid:</p>
<div class="grid-layout">
<div class="grid-sidebar">
<ol>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Menu item 3</li>
</ol>
</div>
<div class="grid-content">
<p>Content</p>
</div>
</div>
The titles of the following existing questions seemed promising, but in the end address other problems:
Can't use max-width to limit content width in css grid column
How to set the maximum width of a column in CSS Grid Layout?
The minmax(...)
function of CSS grid isn't helping either because it doesn't account for relative column widths - at least as far as I tried.
Is there a way to do this with CSS grid at all?
Feels a bit like a hack, but you can achieve this with:
grid-template-columns: auto minmax(calc(100% - 200px), 70%);
Explanation (https://drafts.csswg.org/css-grid/#valdef-grid-template-columns-minmax)
‘minmax(min, max)’
Defines a size range greater than or equal to min and less than or equal to max. If max < min, then max is ignored and minmax(min,max) is treated as min. As a maximum, a value sets the track’s flex factor; it is invalid as a minimum.
This means, the browser will first try to apply the 30% - 70% values. If the calculation of 100% - 200px
is larger then 70% of the whole width it stops growing, which lets the first column exactly take up the space of 200px.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With