Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

html - CSS for high-resolution images on mobile and retina displays

My website images look blurry for users with retina displays. (For example, on the Retina MacBook Pro).

How do I serve high-resolution images to visitors with retina displays, but standard-sized images to everyone else, while keeping the image the same apparent size?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your HTML, create a <div> like so:

<div class="ninjas-image"></div>

And in your CSS, add:

.ninjas-image {
  background-image: url('ninja-devices.png');
  width: 410px;
  height: 450px;
}

@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
  .ninjas-image {
    background-image: url('[email protected]');
    background-size: 410px 450px;
  }
}

The magic here is in the CSS @media query. We have a double-sized image ([email protected]) that we sub-in when the device reports a ‘device pixel ratio’ of 1.5 (144 dpi) or more. Doing it this way allows you to save on bandwidth by delivering the original, smaller image to non-retina devices, and of course it looks great on retina devices.

Note:

This answer was updated in 2016 to reflect best-practice. min-device-pixel-ratio did not make it in to the standard. Instead, min-resolution was added to the standard, but desktop and mobile Safari don't support it at the time of writing, (thus the -webkit-min-device-pixel-ratio fallback). You can check the latest information at: http://caniuse.com/#feat=css-media-resolution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...