CSS3 Transform Scale and Container with Overflow

2020-07-18 07:34发布

I am trying to create a zoom-in functionality for a container with CSS3 Transform (scale) and all seems to work nicely, but when the image is scaled, the overflow only covers a part of the image, leaving the top left part out of the overflow.

Code is as follows:

HTML:

<div class="outer">
    <img id="profile" src="http://flickholdr.com/300/200/" />
</div>
<button class="zoom orig">Original</button>
<button class="zoom x2">x2</button>
<button class="zoom x4">x4</button>

CSS:

.outer          { width: 500px; height: 500px; overflow: auto; text-align: center; background: #eee; }
.outer:before   { content: ''; display: inline-block; vertical-align: middle; height: 100%; }
.outer img      { vertical-align: middle; }

.scale_x2   { -webkit-transform: scale(2); -moz-transform: scale(2); -ms-transform: scale(2); -o-transform: scale(2); transform: scale(2); }
.scale_x4   { -webkit-transform: scale(4); -moz-transform: scale(4); -ms-transform: scale(4); -o-transform: scale(4); transform: scale(4); }

JS:

$(function() {
    $('.zoom').on("click", function() {
        if ($(this).hasClass('orig')) {
            $("#profile").removeClass();
        } else if ($(this).hasClass('x2')) {
            $("#profile").removeClass().addClass('scale_x2');
        } else if ($(this).hasClass('x4')) {
            $("#profile").removeClass().addClass('scale_x4');
        }
    });
});

Check the fiddle here: http://jsfiddle.net/sbaydakov/RhmxV/2/

Any thoughts on how to make this work, so that the whole image is viewable?

Thanks.

2条回答
虎瘦雄心在
2楼-- · 2020-07-18 07:55

The image is scaled from center radially outwards, thus causing the top-left image pixels to disappear. Check this working fiddle http://jsfiddle.net/RhmxV/37/

.scale_x2 {
    margin-left: 150px;
    margin-top: -193px;
    -webkit-transform: scale(2);
    -moz-transform: scale(2);
    -ms-transform: scale(2);
    -o-transform: scale(2);
    transform: scale(2);
}
.scale_x4 {
    margin-left: 450px;
    margin-top: 15px;
    -webkit-transform: scale(4);
    -moz-transform: scale(4);
    -ms-transform: scale(4);
    -o-transform: scale(4);
    transform: scale(4);
}
查看更多
一纸荒年 Trace。
3楼-- · 2020-07-18 08:03

If you want to keep the top left corner where it is, use transform-origin:

transform: scale(2);
transform-origin: top left;
查看更多
登录 后发表回答