Kylee
Kylee

Reputation: 1675

Aligning an element rotated in css

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?

Upvotes: 10

Views: 8590

Answers (3)

Adam
Adam

Reputation: 1

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)+'%)');
        }
    });

Upvotes: 0

shem86
shem86

Reputation: 478

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.

Upvotes: 12

Sergey Kochetov
Sergey Kochetov

Reputation: 390

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.

Upvotes: 1

Related Questions