Html adaptive image size

Responsive Images in CSS

The term “responsive images” has come to mean “responsive images in HTML”, in other words, the srcset and sizes attribute for and the element. But how do the capabilities that these things provide map to CSS? CSS generally wasn’t really involved in the responsive images journey of the last few years. That’s for good reason: CSS already has the tools. Responsive images was, in a sense, just catching up to what CSS could already do. Let’s take a look.

…

One image for 1x displays, a larger image for 2x displays. If we wanted to do that same thing, only as a background-image in CSS, we could do:

.img < background-image: url(examples/images/image-384.jpg); >@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) < .img < background-image: url(examples/images/image-768.jpg); >>

There is a difference here, though. As I understand it, the way srcset is spec’d out is a bit like a suggestion. The attribute and value provide information about what is available and the browser decides what is best at the moment. Or at least, it could, if browsers chose to implement it that way. With a @media query, what is declared shall be. Resolution media queries are fairly well supported: There is another way as well, that is actually closer to how srcset works, and that’s using the image-set() function in CSS:

Читайте также:  Base exception class python

It has a little less support than resolution queries: It’s much closer to srcset , not only because the syntax is similar, but because it allows for the browser to have a say. According to the (still in draft) spec:

The image-set() function allows an author to ignore most of these issues, simply providing multiple resolutions of an image and letting the UA decide which is most appropriate in a given situation.

The sizes attribute in HTML is very directly related to CSS. In fact, it basically says: “This is how I intend to size this image in CSS, I’m just letting you know right now because you might need this information right this second and cannot wait for CSS to download first.” Sample:

But sizes alone doesn’t do anything. You pair it with srcset , which provides known widths, so the browser can make a choice. Let’s assume just a pair of images like:

…
  • If the viewport is less than 375px, use the 375w image.
  • If the viewport is larger than 375px but less than 400px, use the 1500w image (because otherwise we’d be scaling up).
  • At 400px, the image moves to 80vw wide, so it’s safe to use the 375w image for a littttttle bit ( (between 400px and 468px)
  • Over 468px, use the 1500w image.

Which we could write like:

img < background-image: url(small.jpg); >/* Only override this if one of the conditions for the 1500w image is met */ @media (min-width: 375px) and (max-width: 400px), (min-width: 468px) < main < background-image: url(large.jpg); >>

In this exact case, a 2x display, even at a really narrow width like 300px, still requires 600px make that 1.0 minimum quality, so we’d also add that to the logic:

.img < background-image: url(small.jpg); >/* Only override this if one of the conditions for the 1500w image is met */ @media (min-width: 375px) and (max-width: 400px), (min-width: 468px), (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) < .img < background-image: url(large.jpg); >>

The complexity of this skyrockets the more breakpoints (sizes) and the more provided images. And it’s still not a perfect match for what responsive images (in HTML) can do, since it doesn’t allow for browser discretion (e.g. the potential for a browser to consider other factors [i.e. bandwidth] to choose an image).

This kind of thing is a fairly straight-forward conversion to media queries. The exact media queries are right there to copy:

.img < background-image: url(medium.jpg); >@media (min-width: 800px) < .img < background-image: url(large.jpg); >> @media (min-width: 1000px) < .img < background-image: url(extralarge.jpg); >>

No surprise, this can get more complicated, because srcset can do it’s thing within the picture element as well:

.img < background-image: url(small.jpg); >@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) < .img < background-image: url(medium.jpg); >> @media (min-width: 800px) < .img < background-image: url(large.jpg); >> @media (-webkit-min-device-pixel-ratio: 2) and (min-width: 800px), (min-resolution: 192dpi) and (min-width: 800px) < .img < background-image: url(extralarge.jpg); >>

Again, this is just waiting to blow up in complexity as you add a few more images and conditions. Slightly better with image-set() :

Probably? I’d love to see a Sass @mixin that would take all these params, factor in the image sizes (that it figures out itself by hitting the disk), and spits out some quality responsive-images-in-CSS code. Maybe there is even a way to combine resolution queries and image-set() syntaxes?

Are we actually doing this?

I’m curious how many people are actively handling responsive images in CSS. Perhaps even in a middle-ground kinda way of just swapping out larger images at large breakpoints? I wonder if, because picture/srcset is often automated, that actually has a higher adoption rate than responsive images in CSS does?

Источник

How TO — Responsive Images

Responsive images will automatically adjust to fit the size of the screen.

Resize the browser window to see the responsive effect:

Lights

How To Create Responsive Images

Step 1) Add HTML:

Example

Nature

Step 2) Add CSS:

If you want the image to scale both up and down on responsiveness, set the CSS width property to 100% and height to auto:

Example

If you want an image to scale down if it has to, but never scale up to be larger than its original size, use max-width: 100% :

Example

If you want to restrict a responsive image to a maximum size, use the max-width property, with a pixel value of your choice:

Example

Go to our CSS Images Tutorial to learn more about how to style images.

Go to our CSS RWD Tutorial to learn more about responsive web design.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Как создавать адаптивные изображения. Атрибут srcset

Адаптивные изображения автоматически изменяют свой размер, чтобы соответствовать экрану пользователя, что улучшает вид страницы и ускоряет загрузку.

Давайте рассмотрим несколько способов создания адаптивных изображений.

🎓 В статье мы говорим о пикселях и ретина-дисплеях. Если вы не знаете, что это такое — прочитайте статью.

Метод описания плотности экрана

Метод подходит для тех изображений, размер которых фиксирован на экранах повышенной плотности. Это значит, что для некоторых изображений шириной 200px , указанной в HTML, можно загрузить картинку шириной 600px или больше, так как на экране повышенной плотности она будет смотреться намного лучше.

Как сделать изображение адаптивным с помощью srcset

  • Реагировать на ретину — загружать разные картинки для разной плотности пикселей;
  • Реагировать на ширину вьюпорта — загружать разные картинки для разных медиавыражений;
  • Работать с новыми форматами изображений (AVIF и WebP).

Чтобы реализовать метод, используем атрибут srcset для описания плотности экрана. Атрибут srcset позволяет указать несколько вариантов изображений с разными разрешениями или плотностями пикселей. Браузер выбирает наиболее подходящее изображение на основе плотности пикселей экрана устройства, чтобы загрузить его.

Три размера картинки для разных устройств

1x , 2x , 3x — это идентификатор, который указывает плотность экрана для показа определённой картинки. Разработчик выбирает какие идентификаторы нужно указать для разных устройств.

Дескрипторы ширины, высоты и плотности

В атрибуте srcset можно использовать различные виды дескрипторов для указания вариантов изображений в зависимости от конкретных требований.

Дескриптор ширины (w — width descriptor) указывает ширину изображения или вьюпорта, для которого предназначено конкретное изображение. Измеряется в пикселях.

В этом примере medium.jpg имеет дескриптор 1000w , значит изображение предназначено для вьюпортов шириной 1000px, соответственно, large.jpg — изображение для вьюпортов шириной 2000px.

Дескриптор размера (x — pixel density descriptor) указывает отношение между шириной изображения и шириной вьюпорта. Он измеряется в вещественных числах без единицы измерения.

Здесь у medium.jpg дескриптор 1.5x , значит, ширина изображения в полтора раза больше ширины вьюпорта. У large.jpg ширина изображения в два раза больше ширины вьюпорта.

Дескриптор плотности пикселей (dppxdots per pixel descriptor) задаёт плотность пикселей изображения или экрана, для которого предназначена конкретная картинка. Он измеряется в пикселях на дюйм ( ppi ).

Дескриптор 1.5dppx означает, что изображение предназначено для устройств с плотностью 1.5 пикселя на дюйм. Изображение large.jpg подойдёт для устройств с плотностью 2 пикселя на дюйм, например, для планшетов, ноутбуков или мониторов с очень высоким разрешением.

Использование атрибута srcset позволяет создавать адаптивные изображения, которые оптимально подстраиваются под различные устройства и экраны. Когда браузер загружает страницу, он анализирует дескрипторы изображений и выбирает наиболее подходящее на основе характеристик экрана и возможностей браузера.

Кадрирование изображений и тег

Если по дизайну сайта изображение на разных устройствах немного меняется, например, кадрируется или приобретает дополнительные детали, его удобно верстать с помощью тега .

Пример одного логотипа для разных устройств

Как добавить адаптивное изображение с помощью

Указываем открывающий и закрывающий тег . Внутри этого контейнера будем определять разные источники изображений.

Атрибут media описывает условия, при которых будет загружаться соответствующее изображение. Например, media=»(min-width: 1200px)» означает, что изображение logotype-desktop.svg будет загружаться, если ширина экрана равна или больше 1200px .

  • В зависимости от условий задать нужное изображение;
  • Рассказать браузеру о наличии картинок в новых форматах и указать, какая из них подходит к вьюпорту;
  • Кадрировать картинку.

В конце добавляем элемент , который будет использоваться в случае, если браузер не поддерживает тег или не выполняется ни одно из условий, определённых в тегах . Здесь указываем путь к изображению img/logotype-phone.svg и добавляем альтернативный текст с помощью атрибута alt .

      

Материалы по теме

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

Оцените статью