Why is translateY(-50%) needed to center an element which is at top: 50%?

前端 未结 4 1986
悲哀的现实
悲哀的现实 2020-12-07 12:44

I can see that this code works to align a div vertically within its parent element:

.element {
  position: relative;
         


        
4条回答
  •  囚心锁ツ
    2020-12-07 13:44

    While others have provided the answer that the -50 moves the inner element back up half it's own height, I thought this little animation showing the movement to top: 50%; first, followed by transform: translateY(-50%); second, might help.

    @keyframes centerMe {
      0% { top: 0%; transform: translateY(0%); }
      50% { top: 50%; transform: translateY(0%); }
      100% { top: 50%; transform: translateY(-50%); }
    }
    
    .outer {
      position: relative;
      border: solid 1px;
      height: 200px;
      width: 200px;
    }
    
    .inner {
      position: relative;
      background-color: red;
      height: 50px; width: 50px;
      margin: auto;
      animation: centerMe 5s;
      animation-fill-mode: forwards;
    }
    
    /* rules for example */
    .hline,.vline{background:#000;position:absolute}.vline{height:100%;width:1px;left:calc(50% - .5px);top:0}.hline{width:100%;height:1px;top:calc(50% - .5px)}

提交回复
热议问题