Create 'X' with using CSS transform-origin

2019-07-25 06:20发布

问题:

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