html - 为什么以像素指定的 div 宽度变得越来越小?

标签 html css flexbox precision

我有三个 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 表示它们根本不允许收缩。

Updated fiddle

堆栈片段

.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/

相关文章:

html - 在主页中使用 HTML 相对地址

css - Chrome 错误?新行包裹下一个元素

css - Flexbox 之间的行

ios - React Native 中具有固定宽度和可用空间的灵活布局

html - 我们如何定位最合适的 parent 的 child

jquery - 我如何使用 jQuery 改变 div 中的背景颜色?

php - 使用 php 给下拉列表一个默认值

css - 为什么垂直对齐 : middle push my image out of its container?

html - h1 标签中的两行

html - Windows Outlook 0 7' 10' html 电子邮件中图像上的垂直 1px