user197171
user197171

Reputation: 53

Fixed image size despite device pixel ratio

I am trying to find a way to have same size (actual 250 pixels) for an image across all devices/browsers. My problem is with device pixel ratio. On devices with device pixel ratio higher than 1, the image is shown tiny and when you zoom in, it grows bigger (Same would happen if you would zoom into the ordinary browser).

So, my question is: Is there a way to achieve a constant (actual) size image, by using CSS (or less favorably JavaScript)? Is it possible to fix the size and don't allow it to go any bigger or smaller?

Upvotes: 0

Views: 557

Answers (3)

COY
COY

Reputation: 704

So far the best solution I can think of, without heavy (but a little bit) use of javascript is like:

  1. put this after </body>:
    <script type="text/javascript" id="script-after-body">
    document.body.style.setProperty('--device-pixel-ratio', devicePixelRatio);
    window.addEventListener('resize',e=>{
      document.body.style.setProperty('--device-pixel-ratio', devicePixelRatio);
    });
    </script>
    
  2. put this in style of the <img>:
    width: calc(250px / var(--device-pixel-ratio));
    

Compared to a heavily scripted solution, this solution has a limitation that you have to specify a value of the expected image size in CSS.

Upvotes: 0

Dave D
Dave D

Reputation: 11

I believe what you want is to set a consitant ratio of the viewport.

Add this to your <head> :

<meta content="width=device-width, initial-scale=1.0" name="viewport">

Upvotes: 1

Celt
Celt

Reputation: 2548

You could encapsulate the image in a div like this:

<div id='imageDiv'><img src='theImage.png' class='imageclass' /></div>

And then set the size of the div and position of the image with CSS like this:

#imageDiv {
    height: 500px;
    width: 500px;
    overflow: hidden;
}

.imageclass {
    position: absolute;
}

This should keep it the same size for you across all devices.

Upvotes: 0

Related Questions