使用 Flexbox 或 CSS Grid,是否可以根据其中一列的内容调整列的大小?
这就是我想要的:
我有 2 列,main 和 side。
|------------------------container--------------------------|
| |
||----------------------------------------|----------------||
|| main | side ||
||----------------------------------------|----------------||
| |
|-----------------------------------------------------------|
我希望 side 根据其内容自动调整大小,并且我希望 main 的宽度是 side 的两倍, 最低限度。它可以变大,但不能变小。
随着容器的增加,main 将以相同的速率增长,而 side 保持其自动宽度。
|--------------------------container increases----------------------|
| |
||------------------------------------------------|----------------||
|| main increases | side ||
||------------------------------------------------|----------------||
| |
|-------------------------------------------------------------------|
容器可以缩小到边的3倍大,此时main的宽度将是边的两倍>。我希望这是断点。
|--------------------container----------------------|
| |
||--------------------------------|----------------||
|| main | side ||
||--------------------------------|----------------||
| |
|---------------------------------------------------|
如果容器再缩小,我希望列堆叠,现在两列都是 100% 宽度:
|--------------------container--------------------|
| |
||-----------------------------------------------||
|| main ||
||-----------------------------------------------||
||-----------------------------------------------||
|| side ||
||-----------------------------------------------||
| |
|-------------------------------------------------|
这是我尝试过的:
我尝试使用 Flexbox 和 Grid 来实现这一点,但我无法让主列根据侧列确定其大小。
.container-grid {
display: grid;
grid-template-columns: 1fr auto; /* works, but doesn’t wrap when left column gets too small */
/* I also tried the repeat() syntax, but that only worked for similarly-sized columns */
}
.container-flex {
display: flex;
flex-wrap: wrap;
}
.main { flex: 2; } .side { flex: 1; } /* same problem, doesn’t wrap */
.main ( flex: 0 1 auto; } .side { flex: 0 0 auto; } /* wraps columns too early, any time main is smaller than intrinsic width */
我尝试过的唯一可行的解决方案是知道侧栏的固定宽度(我必须在不知道其内容的情况下进行预测),然后使用 3 倍宽度的媒体查询。当然,媒体查询仅适用于窗口宽度,不适用于容器宽度,因此我必须使用容器的任何父元素来计算媒体查询。
.container-grid {
display: grid;
grid-template-columns: 1fr 15em;
}
@media screen and (max-width: 45em) {
.container-grid {
grid-template-columns: 1fr;
}
}
最佳答案
这是一个解决方案,使用 Flexbox,您在 main
上使用 flex-grow 值比在 side
上大得多。
有了这个,side
将在包装时填充父级,并且在宽屏上时,main
上的值要高得多,flex- 方面
的增长 实际上将是零。
结合 main
上的 min-width
是 side
大小的两倍,它会在变小之前换行,并且为此,我们可以使用基于父级宽度的百分比。
所以在这种情况下,main
上的两倍大小将是父级的 2/3,66.666%。
堆栈片段
.container-flex {
display: flex;
flex-wrap: wrap;
}
.main {
flex: 10000;
min-width: 66.666%;
background: lightblue;
}
.side {
flex: 1 0 auto;
background: lightgreen;
}
span {
display: inline-block;
padding: 20px;
}
<div class="container-flex">
<div class="main">
<span>Fill remain, min. twice the "side"</span>
</div>
<div class="side">
<span>Take content size</span>
</div>
</div>
关于css - 是否可以根据内容设置比例网格列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676986/