我在这里有点问题。我有一个 flexbox 容器,里面有不同大小的孩子。根据数量及其内容,子项可能会溢出父项。
我想要的是孩子们缩小,以便他们尝试适应父容器。我通过向孩子添加收缩和溢出属性来做到这一点。到现在为止还挺好。
.container > div {
background-color: orange;
padding: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 1;
}
Run Code Online (Sandbox Code Playgroud)
我最终得到了这样的结果:
现在我希望它们缩小到一定程度(比如 80 像素)。我不在乎它们是否会溢出容器,但我不想渲染任何小于 80px 的图像。
当然,我加min-width: 80px给了孩子……但这是我的问题。我希望孩子们缩小到 80 像素,但我不想要任何已经小于 80 像素的孩子(如 Child1、Child4 和 Child5)我不希望它们被 min-width 属性放大(或者,我希望它们进一步缩小到min-content)
换句话说。我不想要这个:
我很想拥有这样的东西:
我尝试做类似的事情,min-width: min(min-content, 80px)但当然没有用。
这是一个有问题的小代码笔:https ://codepen.io/claudiofpen/pen/QWELVJO
.container > div {
background-color: orange;
padding: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 1;
}
Run Code Online (Sandbox Code Playgroud)
.container {
width: 300px;
border: 1px solid black;
display: flex;
flex-direction: row;
padding: 5px;
}
.container > div {
background-color: orange;
padding: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 1;
min-width: min-content;
}
.container > div:not(:last-child) {
margin-right: 5px;
}
/* I don't want the following css classes, I cannot
tell in before hand which children are going to have
a larger content */
.container > div:nth-child(2),
.container > div:nth-child(3) {
min-width: 80px;
}Run Code Online (Sandbox Code Playgroud)
小智 3
Temani Afif的解决方案解决了确保文本元素不会收缩到指定宽度以下的问题,除非其固有宽度已经低于该宽度(在这种情况下,它使用其固有宽度作为渲染宽度)。但除非所有子元素的指定宽度之和超过容器的宽度,否则它不起作用。
因此,我尝试为每个外部元素提供一个 flex-grow 参数,这样,如果容器有空间,它们就会增长到指定宽度以上。但我还为外部元素设置了最大宽度,设置为其固有的最大内容宽度,因此它们永远不会超出文本的实际大小。因此我在包装中添加了以下样式div。
flex: 1 1 auto;
max-width: max-content;
Run Code Online (Sandbox Code Playgroud)
通过这个调整,我相信它可以解决整个问题。如果容器中有空间,则元素会完全展开。当我们添加更多元素时,较长的元素开始缩小。但它们永远不会缩小到指定宽度以下,因此一旦所有插入的元素缩小到该宽度,容器就会溢出。但以较短宽度开始的元素根本不会弯曲。
我在下面添加了一个例子。
flex: 1 1 auto;
max-width: max-content;
Run Code Online (Sandbox Code Playgroud)
.container {
width: 340px;
border: 1px solid black;
display: flex;
flex-direction: row;
padding: 5px;
}
.container>div {
background-color: orange;
padding: 5px;
flex: 1 1 auto;
width: 80px;
max-width: max-content;
}
.container>div>div {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 100%;
}
.container>div:not(:last-child) {
margin-right: 5px;
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |