CSS Centering with Transform

前端 未结 1 870
有刺的猬
有刺的猬 2020-12-08 20:00

why does centering with transform translate and left 50% center perfectly (with position relative parent) but not right 50%?

Working example:

span[c         


        
相关标签:
1条回答
  • 2020-12-08 20:51

    Because translateX(-50%) moves something back to the left 50% (because of the - negative value), which means it pairs with left: 50%; to center something.

    If you want to use right: 50%; then use that with translateX(50%) to center.

    * {margin:0;}
    span {
      position: absolute;
      top: 50%; right: 50%;
      transform: translate(50%,-50%);
      background: black;
      color: white;
    }
    
    body:after, body:before {
      content: '';
      position: absolute;
      background: red;
    }
    
    body:after {
      top: 50%;
      left: 0; right: 0;
      height: 1px;
    }
    body:before {
      left: 50%;
      top: 0; bottom: 0;
      width: 1px;
    }
    <span>center me</span>

    0 讨论(0)
提交回复
热议问题