如何结合min-width, fit- content和绝对宽度?



我有一个有两个子元素的伸缩容器。这些元素将overflow-x设置为hidden+text-overflow设置为ellipsis,以确保较大的文本将被截断。

我想为它们的宽度设置规则,以确保这些孩子的最小宽度将是固定的大小,如100px对于较大的文本。或者,如果文本本身小于100px,则使用fit-content(或其他等效的)。

我试过以下方法:

.blue {
max-width: 600px;
display: flex;
gap: 2px;
padding: 2px;
box-sizing: border-box;
border: 2px blue solid;
margin-bottom: 2px;
}  
.blue > .red {
text-overflow: ellipsis;
overflow-x: hidden;
white-space: nowrap;
box-sizing: border-box;
border: 2px red solid; 
padding: 10px;
}  
.blue > .red.second {
min-width: 100px;
/* min-width: fit-content; */
/* min-width: min(fit-content, 5rem); */
}
<div class="blue">
<div class="red first">
Some little bit longer text as an example
</div>
<div class="red second">
Another shorter example
</div>
</div>
<div class="blue">
<div class="red first">
Short text
</div>
<div class="red second">
text
</div>
</div>

参见https://jsfiddle.net/arakasi/s15a7pjg/5/获取另一个测试片段。

是否有可能将fit-content100px合并为min-width的一个规则,只考虑较小的规则?

你需要的是max-width: 100px

let blues = document.querySelectorAll(".blue");
let reds = document.querySelectorAll(".red");
let blueView = document.querySelector("#blue_width");
let redView = document.querySelector("#red_width");
/* debugger */
;
document.querySelector("input").oninput = function() {
blueView.textContent = this.value;
blues.forEach((element) => element.style.width = this.value + "px");
let offsets = [];
reds.forEach((element) => offsets.push(element.offsetWidth));
redView.textContent = offsets;
};
document.querySelector("input").oninput();
.blue {
max-width: 600px;
display: flex;
gap: 2px;
padding: 2px;
box-sizing: border-box;
border: 2px blue solid;
margin-bottom: 2px;
}
.red {
text-overflow: ellipsis;
overflow-x: hidden;
white-space: nowrap;
box-sizing: border-box;
border: 2px red solid;
padding: 10px;
max-width: 100px;
}
<div class="blue">
<div class="red first">
Some little bit longer text as an example
</div>
<div class="red second">
Another shorter example
</div>
</div>
<div class="blue">
<div class="red first">
Short text
</div>
<div class="red second">
text
</div>
</div>
Red box's width is <span id="red_width"></span> px
<br><br> Blue box's width is
<input type="range" value="600" min="100" max="600">
<span id="blue_width"></span> px