How to make images resize automatically to fit horizontally

I use the following HTML and CSS codes to make images adjust to the width of their container while automatically adjusting their height to preserve their aspect ratio.

Figure 1

To target all images automatically rather than individually coding each image you can add the following line to your stylesheet instead.

Figure 2

Using the <picture> tag

You can use the <picture> tag to serve different versions of an image or even totally different images based on screen resolution. In the example below, we assume that you have the CSS rule in Figure 2 already in place.

Figure 3

In the above example the desktop version of an image (for example, 640x480) is displayed by default. But when the screen is equal to or less than 400 pixels wide a mobile version (let's say, 320x240) is served. Meanwhile, a link to the original high-resolution image is provided and can be viewed by clicking on the displayed image.

Labels: ,

« Older PostBack to TopNewer Post »