HTML/CSS : How to stop the cursor after the last letter in this animated text?

Viewed 116

I try to animate some text with html and css. For the moment, I've this :

<div id="rectangle"></div>
<p>Hello world</p>
body {
  margin:0
}
#rectangle{
    position: absolue;
    width:100%;
    height:100px;
    background:#1D2024;
}

p {
  margin-top: -60px;
  margin-left: 30%;
  border-right: solid 3px rgba(87, 203, 204,.75);
  white-space: nowrap;
  overflow: hidden;    
  font-family: 'Source Code Pro', monospace;  
  font-size: 28px;
  color: #57CBCC;
}

/* Animation */
p {
  animation: animated-text 4s steps(29,end) 1s 1 normal both,
             animated-cursor 600ms steps(29,end) infinite;
}

/* text animation */

@keyframes animated-text{
  from{width: 0;}
  to{width: 472px;}
}

/* cursor animations */

@keyframes animated-cursor{
  from{border-right-color: rgba(87, 203, 204,.75);}
  to{border-right-color: transparent;}
}

The codepen is here : https://codepen.io/aakhya/pen/EOxqOV

Why the cursor is stopping so far away after the " d " ? Someone could show me how to stopped the cursor just after the d ?

Thanks a lot

1 Answers

The reason the cursor is stopping so far after the letter d is because of these lines of code:

@keyframes animated-text{
  from{width: 0;}
  to{width: 472px;}
}

The code that says "to{width: 472px;}" means that the cursor will start 472px after it starts.

To fix this, you can edit the width so that it stops right after the d.

A potential alternative to your current animation that you might be looking for is the following:

  @keyframes typing {
    0% {
      width: 0
    }
  }
 
  @keyframes blink {
    50% {
      border-color: transparent
    }
  }

If you put this into your code, along with:

animation: typing 2s steps(11), blink .5s infinite alternate;

(editing it to your needs, of course), and add a width to your p tag, it will give you the animation that accomplishes what you need once you figure out the width through experimentation.

If you want one letter to appear at a time, just make the number of steps equal to the number of characters.

Through experimentation, the width of "Hello World" in this case is about 185px, and requires 11 steps. If you want it to appear faster, you can edit the number of seconds in the animation.

p {
  width: 185px;
  border-right: solid 3px rgba(0,255,0,.75);
  white-space: nowrap;
  overflow: hidden;    
  font-family: 'Source Code Pro', monospace;  
  font-size: 28px;
  color: rgba(255,255,255,.70);
}

/* Animation */
p {
animation: typing 2s steps(11), blink .5s infinite alternate;
}

/* text animation */

@keyframes typing{
  0%{
    width: 0
  }
}

/* cursor animations */

 @keyframes blink{
    50% {
      border-color: transparent
    }
  }    
Related