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

前端 未结 9 1727
情歌与酒
情歌与酒 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.
    0 讨论(0)
  • 2020-12-08 04:27

    The solution to this problem is not to use translate at all. When you are translating an element, the percentage you select is based on it's own height.

    If you want to position the element based on the parent's height, use top: 50%;

    So the code will look like this:

    body {
        margin: 0;
        width: 100%;
        height: 100%;
    }
    body > div {
        width: 200px;
        height: 200px;
        background: #ff0;
        position: relative;
    }
    body > div > div {
        position: absolute;
        top: 50%;
        width: 10%;
        height: 10%;
    /*     -webkit-transform: translateY(50%); */
        background: #f00;
    }
    
    0 讨论(0)
  • 2020-12-08 04:29

    Its forked with positioning required on the following URL working sample

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

    notes :

    1. you can absolute positioning of your red square by changing parent element to position relative
    2. then using 50% top and 50% left will position red square according to its upper left corner
    3. using transform:translate(-50%,-50%) will position red square according to its center
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题