F
F
Fridary2018-03-19 19:32:22
css
Fridary, 2018-03-19 19:32:22

How to set size and srcset attributes for IMG to max-width in HTML?

I have an image 50px wide and a container 500px wide. Using the code below, the image is stretched by 100%, i.e. it becomes smeared by 500px even if I set max-width: 100
% put any other larger than 500px, then it will become 500px as width=100% (that is, if < 500px, then the actual size, if >= 500px, then the size is 500px)?
What is the question? I have a blog that dynamically adds new images to an article using php + javascript. Through php, images are saved in sizes 50px, 200px and 500px. Undoubtedly, some uploaded images will be less than 500px, so I do not save them and they do not fall into the srcset (otherwise srcset="image_50.jpg 50w, image_200.jpg 200w, image_500.jpg 500w").

<div style="width: 500px;">
  <img src="image_50.jpg" sizes="100vw" srcset="image_50.jpg 50w" style="max-width:100%;">
</div>

https://jsfiddle.net/baL5cj0k/4/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Odisseya, 2018-03-20
@Odisseya

Set for img:

img {
  object-fit: contain;
  max-width: 500px;
}

Your example https://jsfiddle.net/v7w0jqLj/
For object-fit fallback in IE and EDGE, use polyfill https://github.com/bfred-it/object-fit-images
NB srcset, sizes attributes you can give to browser an alternative choice by the width of the viewport or screen retina - those parameters that the browser knows about. However, nothing is known about the actual size of the image or how the image fits the viewport in the browser.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question