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

前端 未结 9 1742
情歌与酒
情歌与酒 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:22

    Your statement is absolutely right about the percentages coming from the very translated element. Instead of using translate property in your case you should be using absolute positioning to stay relative to the parent div. I absolutely positioned vertically your red div here:(don`t forget about adding position relative to the parent div.It has to be positioned other than static default):

    js fiddle pen here

     body {
        margin: 0;
        width: 100%;
        height: 100%;
        }
     body > div {
        width: 200px;
        height: 200px;
        background: #ff0;
        position: relative;
        }
     body > div > div {
        width: 10%;
        height: 10%;
        -webkit-transform: translateY(-50%);
        background: #f00;
        position: absolute;
        top: 50%;
        }
    

提交回复
热议问题