简体   繁体   中英

Highly Responsive HTML <picture> element VS CSS 'background-image'

I have couple of questions to the patient people, I'm just learning and I did not found any answer about that online. Well there is many topics about each solution but not answering my question.

So, we have two main responsive ways of using images on our websites. First one is HTML only approach and second one is CSS.

This is pure HTML solution that everyone knows, where the image is served not only based on the breaking points but also detecting HI DPI screens and serving high or standard pixel density images. I like this approach so much that I would like to use it every time bit unfortunately it is a bit limited.

<picture>
   <source srcset="img/desktop.jpg 1920w, img/desktop-hi-dpi.jpg 3840w" media="(min-width: 1536px)">
   <source srcset="img/laptop.jpg 1535w, img/laptop-hi-dpi.jpg 3070w" media="(min-width: 1025px) and (max-width: 1535px)">
   <source srcset="img/tablet.jpg 1024w, img/tablet-hi-dpi.jpg 2048w" media="(min-width: 768px) and (max-width: 1024px)">
   <img srcset="img/mobile.jpg 767w, img/mobile-hi-dpi.jpg 1534w" alt="Example Alt Image Description" class="nice-responsive-image">
</picture>

The CSS way:

.container {
    background: #000;
    background-image: url(https://image.jpg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

Now question: Is there any way of detecting the HI DPI screens using CSS only and serve the images in similar way as HTML srcset attributes are able to?

Because using HTML way and image as a background I'm forced to place my content (sitting in another container) on the top of the image container using position:absolute which isn't a proper responsive approach.

So, is the CSS the only way to apply the background to the container using of course multiple media queries to serve the images in proper sizes for the corresponding device?

Yes you are broadly correct. You can target devices with higher pixel densities in CSS using the resolution media query. There is no equivalent "srcSet" or "sizes" attribute.

In practice you probably need a combination of resolution and the older -webkit-min-device-pixel-ratio query as browser support is patchy.

You seem to have done some research already which is great! These links will help you a bit more:

https://caniuse.com/?search=resolution

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/resolution

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/-webkit-device-pixel-ratio

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM