Making Images Behave

Updated: February 17, 2022
No Credit Card Required


You just learned about images and how they're not really block or inline, there's one more important thing that you should know about the image tag. By default, an image doesn't care how big its parent container is, so an image will spill out of its parent if the image is wider than its parent.

For example, here's an image inside a section. I didn't style the image, it's just small. If I inspect the image, I can see how big it is 100 by 100 pixels, my section is 300 pixels wide, because I gave it a width of 300 pixels in my style tags. Now that makes sense, right? Well, that only works because the image is smaller than the section.

This is what it looks like if I were placed that small image with the big image. The image is obviously a lot wider than my section. Now, when I inspect the section, you can see that the image goes outside of the section. Like I said, this is because images don't care how big their parent is. Luckily, this is an easy fix. Just use CSS to tell the image how wide it should be. I can make my image 300 pixels wide, which would stop it from spilling out of my section. But this isn't a good fix, because I have to remember to update my images width if I ever change the width of my section. Instead, I'll give my images a width of 100%. This means it will always be as wide as its parent container.

Let me show you an example of where I use this. On my gallery page. I gave my images a width of 100% so they don't spill out of their sections. Now I can make sure my images behave like I want them to

HTML/CSS AdvancedCoding Exercises, Quizzes and Projects are available at with your free membership