• Home
  • CSS
  • Auto resize image to div size

Auto resize image to div size



Sometimes we want that picture on page shrinks when browser window shrins. This can be easily achieved by using a short css entry.

For a parent element – usually a div – we set the maximum width to 500px. In this example I also set a red frame so that I can see div border.

Next, we set image width to 100% parents width. Image height we set to auto.

The effect is as shown below. Try to change the browser window and see how the photo width is changing with it.

green-parrot-picture


Code is on codepen:

See the Pen YoBwrR by Joanna (@JoannaEl) on CodePen.



Well, the image adjusts its size to the screen size, but it doesn’t change its weight. The photo of the parrot above is 59 KB no matter if it is displayed on a large or a small screen.

In this case, if someone opens the page on the phone, he will needlessly “download” such a large photo, which will not only consume more transfer, but also slow down loading of the page.

The solution is to “serve” the same photo in different sizes, depending on the size of the screen. For users using desktops, we can display a 500px wide picture, for tablets 350px, and for phones 200px. We only need the same photo in several copies. You can change the image source after recognizing the screen size in Javascript, but you can also do it in HTML. Do you want to know how? See my next post:



Joanna

Leave a Reply

Your email address will not be published. Required fields are marked *