我有三个 div
占据了容器的整个宽度。左边和右边的 div
(应该)有一个固定的宽度,比如 300px
。主 div
应该占据剩余空间。但是,如果主 div
中的文本增加,它会以其他两个 div
变得小于 300 像素的方式增长。
CSS
.container {
display:flex;
}
.main {
background:#CCC;
width:auto;
}
.left {
background:#8F8;
width:300px;
}
.right {
background:#F80;
width:300px;
}
HTML
<div class='container'>
<div class='left'>
Left
</div>
<div class='main'>
Main with long enough text to occupy more than a line, and a few more just to be sure.
</div>
<div class='right'>
Right
</div>
</div>
JSFiddle:https://jsfiddle.net/zLLnbo0u/
如果右侧的 div
或正文被删除,则可以看到问题:左侧的 div
自动增加(回到 300 像素)。如何让左右 div
精确到 300 像素,而主要 div
占据剩余空间,而不考虑文本长度?
最佳答案
flex-shrink
属性指定 flex 元素的 flex 收缩因子,并确定 flex 元素相对于 flex 容器中其余 flex 元素的收缩量足够的空间。
它的默认值是 1
,如果您省略它,则意味着所有项都将平均收缩。
因此,如果您将 flex-shrink: 0;
添加到 left
/right
,它们将保持其宽度,因为值 0
表示它们根本不允许收缩。
堆栈片段
.container {
display:flex;
}
.main {
background:#CCC;
width:auto;
}
.left {
flex-shrink: 0;
background:#8F8;
width:300px;
}
.right {
flex-shrink: 0;
background:#F80;
width:300px;
}
<div class='container'>
<div class='left'>
Left
</div>
<div class='main'>
Main with long enough text to occupy more than a line, and a few more just to be sure.
</div>
<div class='right'>
Right
</div>
</div>
关于html - 为什么以像素指定的 div 宽度变得越来越小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44467725/