I’m putting an img tag in a document without knowing the width/height of the corresponding image:
<img src="/myimage.png" />
I want to use CSS to scale the image to exactly half of its “native” size (the size of the underlying image). I can’t figure out how to do this.
- Using
width: 50%would size relative to the containing block, not the image. - I can’t size to a specific pixel width because I don’t know the image size.
-
Since I only need to support WebKit, I’ve tried using a transform:
-webkit-transform: scale(0.5);This adjusts the image nicely, but doesn’t resize the size of the image element itself.
- @Radagaisus suggests using Javascript, which is a good fallback. However this is on an ultra lightweight mobile page so I can’t use jQuery, and dealing with all the onload() handlers manually would be a pain.
As a postscript: why I am doing this? Because I need to handle the Retina display. I can detect it using devicePixelRatio and fill in larger (2x) images, but I need to scale them down to 50% to look correct on the display.
It’s somewhat weird, but it seems that Webkit, at least in newest stable version of Chrome, supports Microsoft’s
zoomproperty. The good news is that its behaviour is closer to what you want.Unfortunately DOM
clientWidthand similar properties still return the original values as if the image was not resized.