Resizable Images that does not break out of container

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

It is great when we create pages that resizes with the browser. However, it is not so great when an user resizes the browser to be smaller than an image. Typically, the image would remain at its fixed width and break out of its container.

This can be fixed by applying …

img { max-width: 100%; }

to the image. This constrains the maximum width of the image to be the width of its container. If the container resizes smaller, the image will accordingly resize smaller to fit the container. If the container resizes larger than the image width, the image will just be as big as its native width.

The image will not scale up, unless you do …

img { width: 100%; }

which in this case would cause the image to be always at the width of its container.

This is known as fluid image. It not only work for images, but works for other media as well. Often designers will use the rule …

img, embed, object, video { max-width: 100%; }

Alternatively, instead of resizing the image, one can hide any portion of the image that falls outside its container by …

img { overflow: hidden; }