Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...