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

前端 未结 4 1999
悲哀的现实
悲哀的现实 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:38

    position: relative;
    top: 50%;
    

    … moves the element down a distance equal to half the height of the parent.

    Since the default position puts the top of the inner element at the top of the outer element, this puts the top of the inner element at the middle of the outer element.

    transform: translateY(-50%);
    

    This moves the inner element back up a distance of half the height of the inner element.

    Combining them puts the middle of the inner element at the middle of the parent element.

提交回复
热议问题