防止浮动 div 的 child 不必要的水平滚动

Prevent unnecessary horizontal scrolling for child of a floated div

我有一个固定高度的浮动 div (class='outer') 和动态内容 (class='inner')。内容的尺寸是事先不知道的。浮动的宽度 div 必须是灵活的,但仍然有一些最大值:

<style>
.outer {
    border: 1px solid;
    height: 200px;
    max-width: 400px;
    overflow: auto;
    float: left
}
.inner {
    height: 300px;
    width: 300px;
    background-color: red
}
</style>
<body>
<div class='outer'>
    <div class='inner'></div>
</div>
<span>Text here</span>
</body>

这通常有效;但是,如果内容高度过高,则会发生以下情况:

  1. .outer 假定内容的宽度,因为它低于其 max-width
  2. .inner 被迫进入 .outerheight,结果出现垂直滚动条。
  3. .inner 被迫进入新的约束宽度,因为 .outer 不会再次调整大小以适应滚动条。
  4. 结果出现了完全不必要的水平滚动条。

fiddle:https://jsfiddle.net/w053kLkw/

有没有办法阻止 overflow 的这种机制,让两个滚动条只在需要时出现?

在 CSS AFAIK 中不可能(你需要 JS,否则你不应该使用浮点数!)。

当您 float 一个项目时,它将从正常 block formatting context 中删除。浮动项目不会遵守 max-width,因为它会缩小到其内容 - 因此需要指定 widthouter

看看下面当我也设置 width: 400px 时会发生什么。

*{
  box-sizing: border-box;
  }
.outer {
    border: 1px solid;
    height: 200px;
    max-width: 400px;
    width: 400px;
    overflow: auto;
    float: left;
}
.inner {
    height: 300px;
    width: 300px;
    background-color: red;
}
<body>
<div class='outer'>
    <div class='inner'></div>
</div>
<div style="clear: both;"></div>
<span>Text here</span>
</body>

解释

根据 W3C 规范,应始终为浮动元素指定宽度(除了 replaced elements 之类的具有隐式宽度的图像)。否则我们将看到不可预测的行为。

请参阅以下部分:浮动项需要宽度吗? 在此 link

If no width is set, the results can be unpredictable. Theoretically, a floated element with an undefined width should shrink to the widest element within it. This could be a word, a sentence or even a single character - and results can vary from browser to browser.

这意味着 outer 将采用 inner- 的宽度,并且由于 overflow 不是 visible,浏览器将按其认为合适的方式运行。