Herrsocke Herrsocke - 1 month ago 9
CSS Question

Why does the image have overflow:hidden?

I'm wondering why

overflow: hidden
is automatically applied in this code. I know it has to do with
float
, but I still don't get why.



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>




Answer

I think that you are looking at one of those edge cases in the CSS specification.

In your example, if you had floated the image to the left, you would see a horizontal scroll bar, as expected.

However, it appears that elements that are floated to the right and cause an overflow condition on the left edge are clipped.

The CSS 2.1 specification alludes to this in the following line:

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

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

The same effect also takes place if you were to use absolute positioning on the image.

Setting the offset to left: 0 would trigger a scroll bar, whereas setting right: 0 instead would force the image to be clipped.

The people who could best answer why browsers work this way are those who actually wrote the CSS rendering engines used in the modern browsers.

Regardless, you raised an interesting point.