Andrejs Gubars Andrejs Gubars - 18 days ago 6
Sass (Sass) Question

Create 'X' with using CSS transform-origin and rotate

I have a small issue, I need to rotate 2 spans and create a perfect 'X'.

I've created a JSfiddle for this. Can you guys help me?

I can't seem to get my head around how much should i transform origin...

HTML

<div class="toggle-btn">
<span></span>
<span></span>
</div>


SASS

.toggle-btn {
width: 38px;
height: 19px;
cursor: pointer;
position: relative;
margin-top: 18px;
text-align: center;
&:after {
content: '';
display: block;
clear: both;
}
span {
height: 2px;
margin: 5px 0px;
background: #333;
width: 100%;
display: block;
transition: .15s ease-in;
text-align: center;
&.toggled {
&:nth-of-type(1) {
transform: rotate(-45deg);
transform-origin: 22px 9px;
}
&:nth-of-type(2) {
transform: rotate(45deg);
transform-origin: 20px -5px;
}
}
}
}


and JS

$('.toggle-btn').on('click',function(){
$(this).find('span').toggleClass('toggled');
});

Answer

This appears to work. I had to adjust the margin to 4px to work. Also, the rotation has to come after the x/y translation because translating afterwards appears to cause it change the point of origin on which it is rotating the element. You can see this behavior by trying a large (100px) translation on just the X axis.

.toggle-btn {
        width: 38px;
        height: 19px;
        cursor: pointer;
        position: relative;
        margin-top: 18px;
        text-align: center;
    overflow: show;
        &:after {
            content: '';
            display: block;
            clear: both;
        }
        span {
            height: 2px;
            margin: 4px 0px;
            background: #333;
            width: 38px;
            display: block;
            transition: .15s ease-in;
            text-align: center;
            &.toggled {
                &:nth-of-type(1) {
                    transform: translate(0px, 3px) rotate(-45deg);
                }
                &:nth-of-type(2) {
                    transform: translate(0px, -3px) rotate(45deg);
                }
            }
        }
    }