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
1.4k views
in Technique[技术] by (71.8m points)

css - Display image at 50% of its "native" size

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

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

1 Reply

0 votes
by (71.8m points)

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.


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

...