CSS Animate text from left to right in div container with overflow hidden

前端 未结 4 1086
我寻月下人不归
我寻月下人不归 2021-02-06 00:45

So i\'ve recently working on some private project, and since i am a huge CSS fan i want to do most of the animations in CSS rather than in JavaScript.

Today i wanted to

4条回答
  •  难免孤独
    2021-02-06 00:54

    You can stop when your text hits the right border

    This solution uses CSS translate.

    The trick is that translate's percentages are corresponding to the current element and left referrs to the parent.

    Make sure your text's display property is NOT inline.

    Downsides of this CSS only approach:

    1. Shorter texts also get animated. To counter that consider JavaScript or make your text min-width: 100%;. This can lead to minimal wiggling by the animation.
    2. All texts get the same amount of animation duration, which can be awful for long texts. Again, consider JavaScript (you'll want to look at scrollWidth) or make many animation classes, which can be very hard to manage.

    .animated {
      overflow: hidden;
      width: 11rem;
      white-space: nowrap;
    }
    
    .animated > * {
      display: inline-block;
      position: relative;
      animation: 3s linear 0s infinite alternate move;
    }
    
    .animated > *.min {
      min-width: 100%;
    }
    
    @keyframes move {
      0%,
      25% {
        transform: translateX(0%);
        left: 0%;
      }
      75%,
      100% {
        transform: translateX(-100%);
        left: 100%;
      }
    }
    
    /* Non-solution styles */
    
    .container {
      display: flex;
      flex-wrap: wrap;
    }
    
    .animated {
      font-size: 2rem;
      font-family: sans-serif;
      border: 0.1rem solid black;
      margin: 1rem;
    }
    
    .animated > * {
      box-sizing: border-box;
      padding: .5rem 1rem;
    }
    Short
    Short
    Some more text
    A really long text to scroll through

提交回复
热议问题