Hello @ivan-josef,
The problem is caused by a conflict between the media query
and the dimensions attribute in the img
tag. In your CSS, you have a media query that starts with min-width: 768px, which triggers styles for screens 768 pixels and wider. However, the sizes property on the image is set to max-width: 768px, meaning the image remains the same size up to and including 768px. In fact your code does this correctly, keeping your image the same up to and until 769px, and your media query effect starts at 768px. As a result, the layout we expect doesn't appear until 769 pixels and above because your img
attribute actually controls 769 pixels to affect the image. To solve this, we need to change the dimensions property to max-width: 767px
and make the image behave consistently without conflicting with the media query.
Like this:
<img
srcset="images/image-product-desktop.jpg 600w, images/image-product-mobile.jpg 686w"
sizes="(max-width: 767px) 686px, 300px" // I changed this line
src="images/image-product-desktop.jpg"
alt="A bottle of perfume surrounded by foliage"
/>
However, Iād like to show you another method that I prefer:
1- Remove the existing img
tag and add this code to the HTML file:
<picture>
<source srcset="images/image-product-desktop.jpg" media="(min-width: 640px)" />
<img
src="images/image-product-mobile.jpg"
alt="A bottle of perfume surrounded by foliage"
/>
</picture>
2- Remove the existing img
selector and add this code to your CSS file:
img {
min-width: 100%;
height: 200px;
object-fit: cover;
}
@media screen and (min-width: 768px) {
/* ... Other CSS selectors ... */
img {
width: 300px;
height: 100%;
}
}
This method seems clearer to me, and it might feel the same for you. Additionally, by using the <picture>
element, our HTML code becomes more semantic.
I also noticed that on small screens there is not enough space on the sides in the horizontal area. To fix this you can add the following code to your .container selector:
.container {
min-height: 100vh;
margin: 10px 16px; // I changed this line
display: flex;
justify-content: center;
align-items: center;
}
This is a great solution š. Congratulations š