如何在CSS网格布局中设置列的最大宽度? [英] How to set the maximum width of a column in CSS Grid Layout?
问题描述
我要实现的目标:
使用 CSS网格布局,以使页面的右栏尺寸来自其内容,但最多不超过窗口宽度的20%。
Using CSS Grid Layout, to have a page with a right column which size is derived from its content, but only up to 20% of the window width.
我认为它将如何工作:
div {
border-style: solid;
}
#container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: 1fr minmax(auto, 20%);
}
<div id="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
的内容时,左列不会折叠:
It looks good, but then when I remove the content of the second div
, the left column does not collapse:
div {
border-style: solid;
}
#container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: 1fr minmax(auto, 20%);
}
<div id="container">
<div>
some content
</div>
<div></div>
</div>
我的问题:
我的印象是,自 minmax()
I was under the impression that since minmax()
(...)定义的大小范围大于或等于最小值,小于
或等于最大值。
(...) defines a size range greater than or equal to min and less than or equal to max.
这意味着在我的情况下,宽度设置为 auto
(= 0
当 div
20%。但是,它保持在20%。为什么会这样呢?
it would mean that in my case the width is set from auto
(= 0
when the div
is empty) to 20%
. It however stays at 20%. Why is it so?
推荐答案
fit-content函数接受一个参数,即最大值。根据其内容,此属性集仍将占用尽可能少的空间,但不超过最大值。
"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."
请参阅此文章:成为CSS网格忍者!
您可以在解决案例的同时仍然使用基于百分比的最大值:
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>
这篇关于如何在CSS网格布局中设置列的最大宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!