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