css - 如何使用 CSS 使一个元素缩小到某一点,然后将兄弟元素缩小到某一点,然后包装元素?
问题描述
我在弹性盒子里有 2 件物品。当有足够的水平空间可用时,我希望右侧元素具有最大宽度,而左侧元素占据所有剩余空间。随着可用宽度的减小,我想缩小左边的元素,直到它达到一定的宽度。然后,我想缩小正确的元素,直到它达到某个最小宽度。那时,我想再次缩小左侧元素,直到它达到不同的最小宽度。之后,我希望元素包装,第一个元素占据它的整个行,第二个元素是它的最大宽度。
我把它称为收缩,因为我是这么想的,但我认为我不能在这里使用 flex-shrink,因为 flex wrapping 发生在 flex 收缩之前。我几乎通过将每个元素的 flex-basis 设置为其最小宽度,将两者的 flex-grow 设置为 1,并在右侧元素上设置最大宽度来实现。但是,这会使两个元素随着可用空间的增加而以相同的速度增长。我不希望右边的元素增长,直到左边的元素达到一定的宽度。下面的片段显示了这一点。
尽管我希望有一个 CSS 解决方案,但我不一定会在这里绑定到 flexbox。如果 CSS 网格或其他一些机制可以完成这项工作,我当然愿意接受。
在下面的代码片段中,在容器 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>
解决方案
在任何地方使用该min-width
属性而不是width
.
推荐阅读
- haskell - 是否可以有递归求和类型,每个“级别”都有不同的值?
- javascript - Shopify 在选择变体时触发功能,但不会覆盖现有功能
- javascript - ReactDom 没有显示任何内容,控制台中也没有错误
- jquery - 在 Adobe Animate 的代码中使用 jQuery 更改动态文本
- asp.net-mvc-4 - 通过存储过程在数据库中执行更改时不调用触发器
- django - 使用 Rest 框架发送响应后执行 Django 模型操作
- javascript - 循环遍历对象并删除空
- c# - 更新 Android 操作系统后 UnityWebRequest 不起作用
- javascript - Bootstrap 4 和 Javascript 函数 - 验证检查后隐藏表单
- php - 致命错误:调用 Codeigniter 中未定义的函数 base_url()