CSS round stretched image width down to nearest multiple of number of actual pixels

Viewed 178

I am rendering a qr code on my website.

I would like the width to expand, to take 50% of its containing space. It's also important to use nearest-neighbor so that the image remains pixelated.

img {
  width: 50vw;
  image-rendering: pixelated;
}

However, the base qr code size is x pixels, let's say 100 as an example.

I intend to round the width of the image down to the nearest multiple of 100 pixels, so that the QR code looks nice and works correctly.

This can be accomplished with JavaScript, but if anyone knows any CSS-only solution that would be great.

Note, however, one more condition: I would like to round to the nearest number of ACTUAL pixels on the screen, not CSS pixels.

For example, if a user zooms their page to 125%, then each CSS pixel will be 1.25 ACTUAL pixels. If I round to 100 CSS pixels, then the qr code of 125 ACTUAL pixels won't look good. In this case, it should be 100 ACTUAL pixels (80 CSS pixels).

Any solutions for this?

1 Answers

Not sure if it will work with your zoom condition but here is an idea using CSS grid where you can have a width equal to n*100px. The trick is to rely on auto-fit and span all the dynamically created column where each column is equal to 100px

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, 100px);
}

img {
  grid-column: 1/-1;
  width: 100%;
}
<div class="box">
  <img src="https://i.stack.imgur.com/JYLPJ.png">
</div>

Related