Home > Software engineering >  How to create a text slide in animation with CSS?
How to create a text slide in animation with CSS?

Time:03-31

So I am trying to create a text reveal / text-slide-in animation.

I've created this:

@keyframes slide {
  0% {
    left: 0;
  }

  100% {
    left: 105%;
  }
}

.text-slide-in:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 105%;
  animation: slide 1.5s ease infinite;
  background: white;
  box-shadow: 0 0 15px white, 0 0 10px white, 0 0 5px white;
}
<h1 >Lorem ipsum dolor, sit amet consectetur adipisicing elit.</h1>

And that is precisely the effect/animation I am after. The problem is that this basically creates an uneccesary width. You can see the horizontal scrollbar on the snippet.

The other problem with this approach becomes clear when adding a background-color to the parent element:

.site-wrap {
  max-width: 700px;
  margin: 0 auto;
}

section {
  padding: 4rem;
  border-radius: 8px;
  background-color: red;
}

@keyframes slide {
  0% {
    width: 100%;
  }

  100% {
    width: 0;
  }
}

.text-slide-in {
  position: relative;
}

.text-slide-in:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  animation: slide 1.5s ease infinite;
  background: white;
  box-shadow: 0 0 15px white, 0 0 10px white, 0 0 5px white;
}
<div >
    <section>
      <h1 >
        Lorem ipsum dolor, sit amet consectetur adipisicing elit.
      </h1>
    </section>
  </div>

As you can see, it will not work when a background-color is set.

I've also tried doing this with transform & translateX css properties, but I cannot get that to work either.

What would be a solid solution in this case?

CodePudding user response:

You could animate the width and start your position on the right instead of animating the left:

@keyframes slide {
  0% {
    width: 100%;
  }

  100% {
    width: 0;
  }
}

.text-slide-in:after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  animation: slide 1.5s ease infinite;
  background: white;
  box-shadow: 0 0 15px white, 0 0 10px white, 0 0 5px white;
}
<h1 >Lorem ipsum dolor, sit amet consectetur adipisicing elit.</h1>

CodePudding user response:

Use clip-path:

@keyframes slide {
  0% {
    clip-path: inset(0 100% 0 0);
  }
  100% {
    clip-path: inset(0    0 0 0);
  }
}

.text-slide-in {
  animation: slide 1.5s ease infinite;
}

body {
 background:linear-gradient(90deg,red,lightblue);
}
<h1 >Lorem ipsum dolor, sit amet consectetur adipisicing elit.</h1>

  • Related