为什么图像有overflow:hidden?

Why does the image have overflow:hidden?

我想知道为什么 overflow: hidden 会自动应用到此代码中。我知道它与 float 有关,但我仍然不明白为什么。

img {
  float: right;
  margin: 0 0 10px 10px;
}
<p>In this example, the image will float to the right in the paragraph, and the text in the paragraph will wrap around the image.</p>
<p>
  <img src="http://www.w3schools.com/css/w3css.gif" alt="W3Schools.com" width="2000" height="140">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
  vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis
  imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.</p>

我认为您正在查看 CSS 规范中的边缘案例之一。

在您的示例中,如果您将图像向左浮动,您会看到一个水平滚动条,正如预期的那样。

但是,向右浮动并导致左边缘溢出的元素似乎被剪裁了。

CSS 2.1 规范在以下行中提到了这一点:

Even if 'overflow' is set to 'visible', content may be clipped to a UA's document window by the native operating environment.

参考:https://www.w3.org/TR/CSS21/visufx.html#overflow

如果您在图像上使用绝对定位,也会产生同样的效果。

将偏移量设置为 left: 0 会触发滚动条,而设置 right: 0 则会强制裁剪图像。

最能回答为什么浏览器以这种方式工作的人是那些实际编写了现代浏览器中使用的 CSS 渲染引擎的人。

无论如何,你提出了一个有趣的观点。

实际上,overflow: hidden 并未在任何地方应用。图像和包含 p 的元素都是 overflow: visible。您可以在开发工具中验证这一点:

但是,通过将 float: right 应用于图像,您已将 overflow 排除在考虑范围之外。换句话说,overflow 属性 没有效果。

考虑内容的流动。

在从左到右的语言模式下,内容向右溢出。它不会向左溢出。

因此,overflow 属性 不适用于左侧,因为 技术上 没有溢出。

来自规范:

11.1.1 Overflow: the overflow property

This property specifies whether content of a block container element is clipped when it overflows the element's box.

同样,在 LTR reading/writing 模式下,内容不会向左溢出。在 RTL 中情况正好相反。使用 CSS direction property 在它们之间切换。

这就是为什么,正如 中所指出的,滚动条适用于 float: left。但是 float: right.

代码中没有滚动条

这里有一些解决方法:

  • Scroll horizontally starting from right to left with CSS overflow:scroll