简体   繁体   中英

How can I scale an element like an image?

When an image is scaled to percentage proportions, it retains its aspect ratio (if done correctly). I need a div to emulate this behavior.

My situation is that I need to accurately position an element in relation to an image. The image is sized to 100% of the browser width, and a variable height. I want to use pixel measurements to size and place a div exactly 800 pixels from the edge of the image, but using the image's pixels as the measurement (not the browser pixels). Is there a way to do this?

It is possible to calculate the horizontal position in percents, but vertical percentages won't work in my case.

I could use Javascript/JQuery or SASS, and those answers are welcome, but I'd prefer a pure-CSS solution.

If it doesn't make sense, here's a jsfiddle with more information: https://jsfiddle.net/ckcmrs1g/1/

I got inspired by this answer: Determine original size of image cross browser?

I tweaked it a bit, put it in a function and called it on load, and on resize, so the size is recalculated when the browser window is being resized.

Here's the functions code:

function fitIn10Pixels() {
    var newImg = new Image();

    newImg.onload = function() {
      var height = newImg.height;
      var width = newImg.width;
      var widthRatio = $(".redbox img").width()/width;
      var heightRatio = $(".redbox img").height()/height;
      var tenFromLeft = 10*widthRatio;
      var tenFromTop = 10*heightRatio;

      $(".bluebox img").css("left",tenFromLeft+"px");
      $(".bluebox img").css("top",tenFromTop+"px");
      $(".bluebox img").css("height",$(".redbox img").height()-2*tenFromTop+"px");
      $(".bluebox img").css("width",$(".redbox img").width()-2*tenFromLeft+"px");
    };

    newImg.src = $(".redbox img")[0].src; // this must be done AFTER setting onload
}

You can take a look at the fiddle here: https://jsfiddle.net/ckcmrs1g/9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM