How to use transform:translateX to move a child element horizontally 100

前端 未结 2 1929
礼貌的吻别
礼貌的吻别 2020-12-24 06:41

All,

I\'d like to be able to use translateX to animate a child element 100% of the way across it\'s parent (i.e., from the left edge to the right edge).

2条回答
  •  悲哀的现实
    2020-12-24 07:23

    I didn't post my idea originally, because it involves creating an additional HTML layer, and expected better solutions to come.

    Since that hasn't happened, I explain my comment. What I meant was this:

    #parent {
        position: relative;
        width: 300px;
        height: 100px;
        background-color: black;
    }
    #wrapper {
        position: absolute;
        width: 100%;
        height: 100px;
        border: solid 1px green;
        transition: all 1s;
    }
    #wrapper:hover {
        -webkit-transform: translateX(100%);
        transform: translateX(100%);
    }
    #child {
        position: absolute;
        width: 20px;
        height: 100px;
        background-color:red;
    }
    #wrapper:hover #child {
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    

    Since the wrapper is 100% width of the parent, translating it 100% works as expected.

    fiddle

    Note that the wrapper is being translated 100% as you stated. However, seems that what you really want is to move the element 100% - width. To achieve this, you have to translate the child also 100% (now this applies to the child width) in the opposite direction.

    Correction: the child should share the transition property of the wrapper:

    #parent {
        position: relative;
        width: 300px;
        height: 100px;
        background-color: black;
    }
    #wrapper {
        position: absolute;
        width: 100%;
        height: 100px;
        border: solid 1px green;
        transition: all 5s;
    }
    #wrapper:hover {
        transform: translateX(100%);
    }
    #child {
        position: absolute;
        width: 50px;
        height: 100px;
        background-color:red;
        transition: inherit;
    }
    #wrapper:hover #child {
        transform: translateX(-100%);
    }
    

提交回复
热议问题