gpt4 book ai didi

html - Flexbox 子项缩小到某个点(但如果不需要就不要扩展)

转载 作者:行者123 更新时间:2023-12-03 13:32:34 25 4
gpt4 key购买 nike

我在这里有点问题。我有一个 flexbox 容器,里面有不同大小的 child 。根据数量及其内容,子项可能会溢出父项。
A container with 5 children (overflowing)
我想要的是 children 缩小,以便他们尝试适应父容器。我通过向 child 添加收缩和溢出属性来做到这一点。到现在为止还挺好。

.container > div {
background-color: orange;
padding: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 1;
}
我最终得到了这样的结果:
A container with 5 shrunk children
现在我想让它们缩小 但在一定程度上 (假设为 80 像素)。我不在乎它们是否会溢出容器,但我不想渲染任何小于 80px 的图像。
当然,我加了 min-width: 80px给 children ……但这是我的问题。我希望 children 缩小到 80 像素,但我不想要任何已经小于 80 像素的 child (如 Child1、Child4 和 Child5)我不希望它们被 min-width 属性放大(或者,我希望它们进一步缩小到 min-content )
换句话说。我不想要这个:
Container with shrunk children (and enlarged ones!)
我很想拥有这样的东西:
enter image description here
我尝试做类似 min-width: min(min-content, 80px) 的事情但当然,没有用。
这是一个有问题的小代码笔: https://codepen.io/claudiofpen/pen/QWELVJO

.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;
}
<div class="container">
<div>Child 1</div>
<div>Longer Child 2</div>
<div>Longer Child 3</div>
<div>Child 4</div>
<div>Child 5</div>
</div>

最佳答案

使用额外的包装器,您可以做到:

.container {
width: 300px;
border: 1px solid black;
display: flex;
flex-direction: row;
padding: 5px;
}

.container > div {
background-color: orange;
padding: 5px;
flex-shrink: 1;
width: 80px;
}

.container > div > div {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
width: 100%;
}

.container > div:not(:last-child) {
margin-right: 5px;
}
<div class="container">
<div><div>Ch 1</div></div>
<div><div>Longer Child 2</div></div>
<div><div>Longer Child 3</div></div>
<div><div>Child 4</div></div>
<div><div>Child 5</div></div>
</div>

关于html - Flexbox 子项缩小到某个点(但如果不需要就不要扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64225800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com