One of the key parts to responsive website design is responsive images. Dynamically resizing text and elements is one thing, but responsive images can be a whole different ballpark. Fortunately, with only a tiny bit of CSS, you can make your images responsive.
First off, I must give credit where credit is due. The gist of this trick is from kirupa.com. Without that tutorial, I could not be writing this one. I recommend reading that when you can. Kirupa does a very good job at explaining everything. I also need to thank rioforce for a quick fix to keep images from changing proportion (you will see why this is bad very soon). But first, the CSS!
(P.S. I also have this snippet available in SCSS
Now, what all does this do? As I said, Kirupa explained it very well, so I suggest you go read his tutorial right now. Go on, I will still be here when you get back. You read it yet? Good, let’s move on.
As both already stated and is clearly visible, the CSS I use on my sites is slightly modified.
- It is wrapped in a media query. My reasoning behind this is simple: I only want responsive images in smaller, phone and tablet screens. Any laptop (except for that netbook fad… *ahem*) made in the last four-five years should be able to view the images full-sized. The same goes for desktops, even ones older than five years. Since they can handle it while the ever-growing phone and tablet usage base cannot, I would rather serve said smaller screens images scaled to them more than doing such to everyone regardless. The max screen value (
800px) is simply the threshold I chose to use. It can be changed as you wish.
- Use of
width. This is the aforementioned small change rioforce made. When using the “plain”
widthproperty, images tend to increase in scale as the screen size get larger, up until the point the media query has not effect. While the images are responsive, this is a more extreme form of responsive. Changing the code to use
max-widthforces the images to remain at the proper scale and resize properly. To demonstrate what I refer to, here is an image from the Triangle Land GitHub Pages annex. The left half shows an image when the screen uses an 768×1024 resolution (a tablet in landscape mode) with the page using the
widthproperty, while the right half is the same image at the same resolution, but this time the page is using the
As you can see, using
widthmakes a difference.
I have nothing else to add here, so that will do it for this tutorial! Catch you later, everyone!