Problem with @keyframes CSS

4

I'm doing an animation with CSS but the effect is correct only in the first word of the text and the rest is not. Would anyone know the reason for this?

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>
    
asked by anonymous 27.09.2018 / 20:12

2 answers

4

It's like @AndersonCarlosWoss commented. Spaces are breaking text in rows because the element does not have enough width to display the rest of the text on the same line as the width of the element is changed, and overflow: hidden hides the bottom lines. When the element 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 h3 to avoid the 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>
    
27.09.2018 / 20:29
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>
    
27.09.2018 / 20:33