Translate X and Y percentage values based on elements height and width?

前端 未结 9 1746
情歌与酒
情歌与酒 2020-12-08 03:29

Translating an elements Y axis 50% will move it down 50% of its own height, not 50% of the parents height as I would expect. How do I tell a translating element to base it\'

9条回答
  •  一整个雨季
    2020-12-08 04:27

    What works for me using only CSS is:

    .child {
        position: relative;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    
        /* Backward compatibility */
        -webkit-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        -o-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
    }
    

    How it works:

    • top and left positioning move child widget according to parent coordinates. Child widget's top-left corner will appear exactly in the center of parent (this is not what we want at this time).
    • translation will move child widget -50% to top and left based on its size (not the parent). It means, widget's center point will be moved exactly where top-left point was - which previously was set up as center of a parent, and this is what we want.

提交回复
热议问题