Aligning an element rotated in css

吃可爱长大的小学妹 提交于 2020-01-14 08:43:20

问题


I trying to rotate a div on a page and have it rest right up against the left side of its parent element (the body in this case). I know about transform-origin but no matter what values I insert it doesn't align correctly.

http://jsfiddle.net/QpHCM/

HTML

<div class="handle">Text</div>

CSS (Sass)

$transform: rotate(90deg);
$transform-origin: 0 0;

body {
    border: 1px solid red;
}

.handle {
    width: 50px;
    height: 15px;
    background: blue;
    color: white;
    text-align: center;
    padding: 5px;
    line-height: 15px;
    transform: $transform;
    -moz-transform: $transform;
    -webkit-transform: $transform;
    transform-origin: $transform-origin;
    -moz-transform-origin: $transform-origin;
    -webkit-transform-origin: $transform-origin;
}

This is driving me mad. Can anyone get the rotated element aligned to top: 0, left:0 in the body when rotated?


回答1:


Since the rotation is around the center of the element, its not aligned with left: 0.

use:

$transform: rotate(90deg) translate(0, -25px);

the negative half of element width gets you there.

working example.




回答2:


Check my solution ($transform-origin: 12px 11px;): http://jsfiddle.net/QpHCM/1/ I don't actually know why does it work in this way but it works.




回答3:


Here's what I did to achieve a similar functionality.

var rotateStep = 0;
    $('#rotateIcon').click(function() {
        rotateStep += 1;
        var img = $("#rxImage");
        if(rotateStep % 4 == 0){
            img.css('transform-origin', 'top left');
            img.css('transform', 'rotate('+ rotateStep*90 +'deg) translate(0%, 0%)');
        }else if(rotateStep % 4 == 1){
            img.css('transform-origin', 'bottom left');
            img.css('transform', 'rotate('+ rotateStep*90 +'deg) translate(-'+(img.height() / img.width() * 100)+'%, 0%)');
        }else if(rotateStep % 4 == 2){
            img.css('transform-origin', 'bottom right');
            img.css('transform', 'rotate('+ rotateStep*90 +'deg) translate(100%, 100%)');
        }else if(rotateStep % 4 == 3){
            img.css('transform-origin', 'top right');
            img.css('transform', 'rotate('+ rotateStep*90 +'deg) translate(0%, -'+((img.width() / img.height()) * 100)+'%)');
        }
    });


来源:https://stackoverflow.com/questions/19185390/aligning-an-element-rotated-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!