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

前提是你 提交于 2019-12-11 04:15:58

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/40728886/create-x-with-using-css-transform-origin-and-rotate

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