【发布时间】:2021-10-03 20:49:44
【问题描述】:
我在一个弹性盒子里有 2 个项目。当有足够的水平空间可用时,我希望右侧元素具有最大宽度,而左侧元素占据所有剩余空间。随着可用宽度的减小,我想缩小左边的元素,直到它达到一定的宽度。然后,我想缩小右边的元素,直到它达到某个最小宽度。那时,我想再次缩小左边的元素,直到它达到不同的最小宽度。之后,我希望元素进行换行,第一个元素占据其整行,第二个元素为其最大宽度。
我把它称为收缩,因为我是这么想的,但我不认为我可以在这里使用 flex-shrink,因为 flex wrapping 发生在 flex 收缩之前。我几乎通过将每个元素的 flex-basis 设置为其最小宽度,将 flex-grow 都设置为 1,并在右侧元素上设置最大宽度来达到目标。但是,这使得这两个元素随着可用空间的增加而以相同的速度增长。我不希望右边的元素增长,直到左边的元素达到一定的宽度。下面的 sn-p 显示了这一点。
虽然我希望有一个 CSS 解决方案,但我不一定会在这里使用 flexbox。如果 CSS 网格或其他一些机制可以实现这一点,我当然愿意。
在下面的 sn-p 中,在容器 div 上设置的宽度只是为了模拟它们可能的宽度。在实际代码中,这些宽度都将设置为auto,实际宽度将由浏览器的视口大小和页面上的其他动态元素决定。
div {
height: 175px;
}
.container {
background-color: grey;
display: flex;
flex-wrap: wrap;
width: 700px;
margin-bottom: 20px;
}
.high-width {
width: 600px;
}
.med-high-width {
width: 500px;
}
.med-low-width {
width: 450px;
}
.low-width {
width: 400px;
}
.content {
background-color: lightblue;
flex: 1 0 350px;
}
.sidebar {
background-color: lightgreen;
flex: 1 0 100px;
max-width: 200px;
}
.wrong {
background-color: red;
}
<div class="container">
<div class="content">This fills the remaining space (500px), which is what I want!</div>
<div class="sidebar">This is 200px wide, which is what I want!</div>
</div>
<div class="container high-width">
<div class="content">This is 425px wide but I want it it to be 450px (Once the content gets down to 450px wide, I want only the sidebar to start shrinking until it hits its min width)</div>
<div class="sidebar wrong">This is 175px wide but I want it to be 150px (Once the content gets down to 450px wide, I want only the sidebar to start shrinking until it hits its min width)</div>
</div>
<div class="container med-high-width">
<div class="content">This fills the remaining space, but that is 375px when I want it to be 400px (Once the sidebar is at its min-width, the content should start shrinking again)</div>
<div class="sidebar wrong">This is 125px wide but I want it to be 100px (Once the content gets down to 450px wide, I want the sidebar to start shrinking until it hits its min width)</div>
</div>
<div class="container med-low-width">
<div class="content">This fills the remaining space (350px), which is what I want!</div>
<div class="sidebar">This is 100px wide, which is what I want!</div>
</div>
<div class="container low-width">
<div class="content">This is on a row by itself, full width (400p), which is what I want!</div>
<div class="sidebar">This is on a row by itself and 200px wide, which is what I want!</div>
</div>
【问题讨论】: