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

前端 未结 2 1802
礼貌的吻别
礼貌的吻别 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:32

    There's a pretty cool solution to this problem using Flexbox. The key is to take advantage of the flex-grow property.

    Say you have some HTML that looks like this:

    First, give .flex-container the basic display: flex property, and set its flex-direction to row. Set the positioning of the child elements to relative, so they will sit next to each other inside .flex-container.

    By default, the flex-grow property is set to 0, which is exactly what we want at the beginning. This means that .flex-spacer and .slider will only have their normal dimensions to begin with. We simply keep .flex-spacer empty, and it will have a width of 0.

    Now for the animation. We only need two CSS rules to make it work: add a transition to .flex-spacer and set flex-grow to 1 on .flex-spacer during some event. The second rule gives all of the unused width inside .flex-container to the width of .flex-spacer, and the first rule animates the change in width. The .slider element gets pushed along to the edge of .flex-container.

    The CSS looks something like this - I added a background to .flex-spacer to make its presence a little more obvious, and set flex-grow to 1 when the user hovers over .flex-container:

    body * {
      box-sizing: border-box;
    }
    
    .flex-container {
      cursor: pointer;
      display: flex;
      flex-flow: row nowrap;
      width: 100%;
      border: 2px solid #444;
      border-radius: 3px;
    }
    
    .flex-spacer,
    .slider {
      flex-grow: 0;
      position: relative;
    }
    
    .slider {
      padding: 25px;
      background-color: #0DD;
    }
    
    .flex-spacer {
      background-color: #DDD;
      transition: all .4s ease-out;
    }
    
    .flex-container:hover .flex-spacer {
      flex-grow: 1;
    }

    Flexbox makes this pretty configurable, too. For example, say we want .slider to move from right to left, instead. All we have to do is switch the flex-direction property in .flex-container to row-reverse, and we're done!

    Feel free to play with it in this pen.

    Keep in mind that things can get a little trickier if we want animations for different types of events. For example, I came across this issue when trying to animate a label when a user types in an input element. A little more HTML and CSS is needed to make it work (I used some JS, as well), but the concept is the same.

    Here's another pen, this time in the context of a form with input.

提交回复
热议问题