使用CSS变换源创建“ X”并旋转 [英] Create 'X' with using CSS transform-origin and rotate

查看:65
本文介绍了使用CSS变换源创建“ X”并旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题,我需要旋转2个跨度并创建一个完美的'X'。

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

我创建了一个 JSfiddle 。你们能帮我吗?

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;
      }
    }
  }
}

JS

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


推荐答案

这似乎可行。我不得不将边距调整为4px 。旋转需要在x / y平移之后进行,因为旋转后的平移似乎会更改元素旋转的原点,而不是元素的原点。您可以通过在旋转后尝试较大的(100px)x平移来观察此行为。

This appears to work. I had to adjust the margin to 4px. The rotation needs to come after the x/y translation because translating after the rotation appears to change the point of origin on which the element is rotating instead of origin of the element. You can observe this behavior by trying a large (100px) x-translation after the rotation.

.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);
                }
            }
        }
    }

这篇关于使用CSS变换源创建“ X”并旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆