Typewriter Effect
Some use JavaScript, which may sometimes be preferable (literally adding a character at a time feels more like a real typewriter) and sometimes not be (potential accessibility concerns).
Came across this SCSS @mixin from Brandon McConnell with powerful options that can identify multiple strings, speed, caret configurations, pauses, and all kinds of other things.
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
Very clever way to do this with pure CSS. I actually wrote a jQuery plugin a while back (http://macarthur.me/typeit) that does this same thing with a few more features for customization, but it’s obviously dependent on jQuery. I might pull a few tips from your JS examples if I ever want to make a vanilla JS version — particularly the CSS injection idea. Some of it relies on jQuery to do what CSS animations could do natively, and I’d like to see that changed.
Sorry, I moved the site to a dedicated URL and it looks like the redirect was down for a while. The new location is https://typeitjs.com, but that redirect should also be working now.
// Love dynamically typed text? You’re gonna love this
// Edit these strings to see them typed on the screen:
$strings: (
“CSS typed this string!”
“It typed this one too ”
“Enjoy ☕”
); // now for some timing (all in seconds)
$durCharFwd: 0.10; // character typed
$durFullGap: 5.00; // time between typed/delete
$durCharBwd: 0.08; // character deleted
$durDoneGap: 5.20; // time between strings // initializing some variables and functions ✊
$charCount: 0; $durTotal: 0;
@each $string in $strings $charCount: $charCount + str-length($string);
$durTotal: $durTotal
+ (str-length($string) * ($durCharFwd + $durCharBwd))
+ $durFullGap + $durDoneGap;
>
@function percent($string, $letter) $stringsPast: $string – 1; $time: 0;
@while $stringsPast > 0 $time: $time
+ (($durCharFwd + $durCharBwd) * (str-length(nth($strings, $stringsPast))))
+ $durFullGap + $durDoneGap;
$stringsPast: $stringsPast – 1;
>
@if $letter <= str-length(nth($strings, $string)) $time: $time
+ ($durCharFwd * ($letter – 1));
> @else $time: $time
+ ($durCharFwd * str-length(nth($strings, $string)))
+ $durFullGap
+ ($durCharBwd * ($letter – str-length(nth($strings, $string))));
>
@return $time / $durTotal * 100 + “%”;
>
$currentPercentage: 0;
// now THIS is where the magic happens… ✨
@keyframes typed @for $i from 1 through length($strings) // @for $j from 1 through (str-length(nth($strings, $i)) * 2 – 1) @for $j from 1 through (str-length(nth($strings, $i)) * 2) /* string #, char # */
@if $j < str-length(nth($strings, $i)) * 2 < // not last character deleted
#
> @else content: quote(#
>
>
> @else @if $i < length($strings) < // not last string
#
>
> @else < // last string
#
>
>
>
>
>
>
@keyframes beam-blink 75% < border-color: transparent; >
>
* < backface-visibility: hidden; >
html, body < height: 100%; >
body display: flex;
align-items: center;
justify-content: center;
background-color: #000;
background-image: // skeuomorphism anyone?
radial-gradient(rgba(#fff, 0.125), rgba(#fff, 0)),
linear-gradient(to bottom, #000, #000 2px, #111 3px);
background-repeat: repeat-y;
background-position: center center;
background-size: cover, 100% 3px;
font-size: calc(10px + 2vw);
font-family: ‘VT323’, monospace, sans-serif;
color: #3f3; // hacker green
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
&::after content: “”; // zero-width space to retain element height when empty
position: relative;
top: -13px;
@media (max-width: 575px) < top: -33px; >
display: inline-block;
padding-right: 3px;
padding-right: calc(3px + 0.1vw);
border-right: 10px solid rgba(#3f3, 0.75);
border-right: calc(1.1vw + 4px) solid rgba(#3f3, 0.75);
text-shadow: 0 0 5px rgba(51, 255, 51, 0.75);
white-space: nowrap;
animation: typed # linear 1s infinite, beam-blink 1s infinite;
>
&::before < // just generating some useful stats here
content: “# strings / # chars / #s duration”;
@media (max-width: 575px) content: “# strings \A # chars \A #s duration”;
>
display: block;
position: absolute;
bottom: 0;
width: 100%;
padding: 3px 0;
background: #00f; // aquaman blue
color: #fff; // Brandon-McConnell white
text-align: center;
font-size: 18px;
letter-spacing: 0.7px;
white-space: pre-wrap;
>
>
Love the CSS-only version! Ingenius. I too created a typing library – with no jquery (or any other) dependency – https://github.com/qodesmith/typer There is a link to a demo on the abive github page. It has a robust api that offers a lot of natural “typing” use-cases: back, continue, etc. I hope you guys find it useful!
Very cool trick! I’m working on a personal project right now and trying to accomplish a similar functionality to this (like typed.js) dynamically using only CSS/SCSS via ::before/::after and the content property. Because the property isn’t animatable, it will automatically reveal each character without having to do any width or overflow changes and hiding/showing text. I have a few keyframe bugs I’m working through now but it’s pretty close. Check it out:
Thanks so much for this, I have on problem. I build alot of websites for clients using squarespace and for some reason when implementing this after typing whats in HTML, the cursor keeps on going. Someone care to help me out?
Hey Brandon! The CSS snippet relies on a fine balance between the length of the content and the number of steps in the animation. If you’re finding that the cursor continues past the container, then try adjusting the number of steps in the animation so that is corresponds with the length of the content using the effect.
Эффект печатающегося текста на чистом CSS
Вероятно вы уже встречались с такими эффектами, как просматривали, так и материал, но в большинстве случаев он идет с javascript. Но в нашем материале как видим все 2 варианта идут на чистом стиле CSS. Просто еще одна реализация стилистики для анимации ввода текста с использованием псевдоэлементов и анимации CSS3.
Где изначально задаем знаки в HTML, но в самих стилях идет дизайн, также можно выставить скорость, это с каким промежутком станет появляться знак. Эффект впечатляющий, который не сложно реализовать, где можно посмотреть на demo странице, как изначально выглядит, хотя как поняли из описания, что все отлично редактируется под каждый стиль.
Есть много вариантов для анимированного набор печати, где текст прописывают в CSS, и совершенно другая анимация, так что можете посмотреть и выбрать тот метод, который больше подходит.
Приступаем к установке:
Создание анимации для печатающегося текст:
Эффект печатающегося текста
.satodsan-uvemopag h1 <
color: #eaeaf9;
font-family: monospace;
overflow: hidden;
border-right: .17em solid #e29508;
white-space: nowrap;
margin: 0 auto;
letter-spacing: .17em;
animation:
typing 3.5s steps(30, end),
blink-caret .7s step-end infinite;
>
На этом все, здесь как видим на чистом стиле выводит знаки.
Способ создания эффекта печатающегося текста:
Пишущая машинка анимация чистый CSS
.dsongentom <
position: relative;
top: 50%;
width: 30em;
margin: 0 auto;
border-right: 2px solid rgba(255,255,255,.75);
font-size: 180%;
text-align: center;
white-space: nowrap;
overflow: hidden;
transform: translateY(-50%);
>
.desetungavon <
animation: typewriter 4s steps(44) 1s 1 normal both,
blinkTextCursor 500ms steps(44) infinite normal;
>
@keyframes typewriter <
from
to
>
@keyframes blinkTextCursor <
from
to
>
Немного похожий на первый вариант, но с небольшими изменениями. Вообще при правильном использовании CSS-анимация у вас появляется возможность как можно больше добавить интереса и индивидуальность интернет ресурсу.
doctor Brain
В настоящее время CSS является очень мощным инструментом веб-разработчика, позволяющим создать большое количество качественных визуальных эффектов, не привлекая JavaScript. CSS позволяет контролировать значительное количество параметров, определяющий дизайн Вашего веб-ресурса: стиль графики, цветовое решение, визуальные эффекты.
В этой статье мы разберем эффект набора текста на пишущей машинке с помощью CSS, без какого-либо обращения к JavaScript.
Код HTML содержит всего два блока:
@import url('https://fonts.googleapis.com/css2?family=Anonymous+Pro&display=swap'); .container < height: 100vh; display: flex; align-items: center; justify-content: center; >.type < width: 45rem; margin: 0; padding: 0; #background: #555; animation: typing 8s steps(45), blink 0.5s step-end infinite alternate; white-space: nowrap; overflow: hidden; border-right: 3px solid; font-family: 'Anonymous Pro', monospace; font-size: 2em; text-align: left; >@keyframes typing < from < width: 0 >> @keyframes blink < 50% < border-color: transparent >>
Обратим внимание на ключевые моменты CSS-кода:
- в нашем примере для того, чтобы получить достоверный эффект пишущей машинки, используется моноширный шрифт,
- так же необходимо обратить внимание и поэкспериментировать с такими параметром CSS-анимации, как steps
Готовый пример можно посмотреть на codepen:
Написано по материалам статьи Stokry “Typing effect without Javascript”.
Новые публикации
JavaScript: сохраняем страницу в pdf
HTML: Полезные примеры
CSS: Ускоряем загрузку страницы
JavaScript: 5 странностей
JavaScript: конструктор сортировщиков
Категории
О нас
Frontend & Backend. Статьи, обзоры, заметки, код, уроки.
© 2021 dr.Brain .
мир глазами веб-разработчика