1

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!

Ben
  • 15
  • 2
  • 6
  • Does this answer your question? [How do I auto-resize an image to fit a 'div' container?](https://stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container) – alexfertel Jun 07 '20 at 21:50

2 Answers2

4

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.

manneJan89
  • 1,004
  • 8
  • 27
1

You shouldn't have your styles inline for your logo.

<source srcset="logo3.jpg" media="(max-width: 480px)">

Would be much better off like this

.logo3 {
  width: 220px;
}
<img class="logo3" src="logo3.jpg">

I would just have the logo in place once and size it differently based on the screen like this

.logo3 {
  width: 220px;
}

@media only screen and (max-width: 500px) {
.logo3 {
  width: 480px;
}
}
<img class="logo3" src="logo3.jpg">

Let me know if this is helpful.