Problem with @keyframes CSS

Asked

Viewed 86 times

4

I’m making an animation with CSS but the effect is correct only in the first word of the text and the rest not. Would anyone know why this occurs?

h3{
  position: absolute;
  font-family: consolas;
  letter-spacing: 5px;
  color: transparent;
}

h3:before{
  content: attr(data-text);
  position: absolute;
  overflow: hidden;
  border-right: solid 1px #000;
  width: 100%;
  height: 100%;
  animation: type 10s steps(27) infinite;
  color: #000;
}

@keyframes type{
  0%{
    width: 0;
  }
  50%{
    width: 100%;
  }
  100%{
    width: 0;
  }
}
<h3 data-text="Efeito CSS - Escrever Texto">
  Efeito CSS - Escrever Texto
</h3>

  • Because, probably, as you are changing the width of the element, the text breaks into several lines, only appearing the text on the same line when the element has sufficient width for this.

  • @Andersoncarloswoss What I’m finding strange is that the first word gets the right effect!

  • Because the browser breaks the word in half if the element is smaller than the word. Try working with the property word-wrap.

2 answers

4


It’s like @Andersoncarloswoss commented. Spaces are breaking text into lines because the element is not wide enough to display the rest of the text on the same line as the width of the element is changed, and the overflow: hidden hides the bottom lines. When the widget has a width that fits a word after a space, the word appears at once.

The effect works on the first word because it is at the beginning of the line.

If you put a white-space: nowrap; in the h3 to avoid line break you will see that the effect works correctly:

h3{
  position: absolute;
  font-family: consolas;
  letter-spacing: 5px;
  color: transparent;
  white-space: nowrap;
}

h3:before{
  content: attr(data-text);
  position: absolute;
  overflow: hidden;
  border-right: solid 1px #000;
  width: 100%;
  height: 100%;
  animation: type 10s steps(27) infinite;
  color: #000;
}

@keyframes type{
  0%{
    width: 0;
  }
  50%{
    width: 100%;
  }
  100%{
    width: 0;
  }
}
<h3 data-text="Efeito CSS - Escrever Texto">
  Efeito CSS - Escrever Texto
</h3>

  • This was it, sam. Thanks man!!

4

An alternative to Sam’s response is to use the CSS property word-break with the value break-all.

h3 {
  position: absolute;
  font-family: consolas;
  letter-spacing: 5px;
  color: transparent;
}

h3:before {
  content: attr(data-text);
  position: absolute;
  overflow: hidden;
  border-right: solid 1px #000;
  width: 100%;
  height: 100%;
  animation: type 10s steps(27) infinite;
  color: #000;
  word-break: break-all;  /* <--- */
}

@keyframes type {
  0%   { width: 0; }
  50%  { width: 100%; }
  100% { width: 0; }
}
<h3 data-text="Efeito CSS - Escrever Texto">
  Efeito CSS - Escrever Texto
</h3>

  • Good Fernando, learning one more here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.