Why is this image overflowing its <div> container?

Hi everyone

Here’s a very basic Codepen with an image inside a

container: https://codepen.io/LuDon89/pen/xxeWMbK

This is probably a very basic CSS question but I’m trying to figure out why the image’s height is bigger than its <div> container once the viewport gets wide enough for the margins to appear. In that case, the picture is 450px tall whereas the <div> is only 400px tall.

I’ve added another container with an orange background in the pen to show that the image is overflowing. It’s ugly but you get the point.

Thanks for your help!

Welcome to the forum @Ludon89

The img element is overflowing because there is no overflow property for .container

Currently the default is set to visible.

Happy coding

1 Like

Hey, thanks for your reply. This doesn’t exactly answer what I’m wondering about though:

There’s a thing I’m not sure I understand about the way images behave. I would think that setting their height (or width for that matter) to 100% would prevent them from overflowing their container, just like setting the height on a <div> container does. Why is it not the case? Do images behave in a special way?

I’ve added another inner container to my CodePen with a width and height of 100% to show what I would expect would happen.

Thanks again

Hi there! In your case max-height: 400px; of .container element is the cause of this overflow. Your picture is 800x600 px
To wrap the picture in the container you have to set only width or max-width to container and width: 100% to the image, that’s enough.

Image

I hope this helps

1 Like

Mhhh… I see. So i guess images don’t behave like <div>s anyway…?

If the image was a div it would be 0 in height. max-height on the parent will not let the child element compute its height using a percentage unit. You also do not want a max height because the image height should be based on its width to maintain the correct aspect ratio (unless you allow cropping using object-fit: cover). All you should need on the container is the max-width.

Images are replacement elements and they have a intrinsic size. The only time you will see images collapse is if you use the background-image property (because the element isn’t in the document).

1 Like

ok i see, i didn’t know that the parent needed a specific height so that the child can compute its own height. Thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.