简体   繁体   中英

CSS3 image rotation and reposition to fit in div

I'll start with JS Fiddle:

http://jsfiddle.net/zy2xy/4/

<div id="page" style="position: relative; background: #ccc; width: 500px; height: 600px;">
    <div id="container" style="top: 50px; left: 100px; width: 200px; height: 200px; position: absolute; background: #fff;"> 
        <img src="http://lorempixel.com/200/100/">
    </div>
</div>​​​​​​​​​

I've got a whole page div #page , and inside that another div #container positioned absolute against #page .

What I want to achieve, is to rotate image inside it 90deg , 180deg or 270deg but always move that image to top left corner of #container .

I tried a little bit with transform-origin but I couldn't find any solution.

Set the position:absolute to the image

Then calculate the angle.. If it's 90 or 270 then set the left and top attributes for the image.

Code

$('a').click(function(e) {
    e.preventDefault();
    var angle = $(this).attr("id");
    console.log("angle");
    var $container = $('#container');
    var left = 0;
    var top = 0;
    if(+angle === 90 || +angle === 270){
        top = 50;
        left = -50;
    }
    $("#my_image").css({
      transform: 'rotate('+angle+'deg)',
      '-moz-transform': 'rotate('+angle+'deg)',
      '-webkit-transform': 'rotate('+angle+'deg)',
        'top' : top + 'px',
        'left' : left + 'px'
    });
}).click();​  // Fire click on DOM ready

Check Fiddle

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