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!
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.