Search code examples
htmlcssimagemedia-queriesimage-resizing

How to resize an image for smaller screens?


I am trying to resize an image so that it displays appropriately for smaller screens. Currently the image can scale down but it's too small for the smaller screens. First I tried using a media query then alternatively the picture tag. See below:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<picture>
<source srcset="logo3.jpg" media="(max-width: 480px)">
<source srcset="logo2.jpg">
<img class="logo" src="logo2.jpg" alt="name" width="220">
</picture>

OR

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<img class="logo" src="logo2.jpg" alt="name" width="220">

CSS

.logo {
display: block;
margin: 0 auto 0 auto;
width: 16%;
}

img{
width:100%;
height:auto;
}

@media screen and (max-width:480px){
.logo {
width: 150px;
}

I have been playing around with both the code and image sizes for a few hours now but nothing seems to work.

Is there something wrong with the code?

Please can someone provide me with a solution or point me in the right direction?

Ps. I am a beginner so please make it beginner-friendly :) thanks!


Solution

  • For images (or anything for that matter) your sizes cannot be in px, it has to be in %.

    So if you want your image to scale, but not be allowed to be bigger than x, then you can do the following:

    img{
       width: 100%;
       max-width: 500px;
    }
    

    Now your image will always be 500px, but when your screen size becomes smaller than 500px, the image will take up 100% of the screen width.

    This also eliminates the need to create media queries for everything.