Creating a Typewriter Text Display Effect with HTML and CSS

HTML and CSS provide a treasure trove of possibilities when it comes to webpage design. A popular design effect that adds a unique and dynamic feel to text is the ‘Typewriter Effect.’ This tutorial will guide you through creating this vintage typewriter animation using HTML and CSS.

Step 1: HTML Setup

The foundation of our typewriter effect is simple HTML. The following HTML code creates a division (div) with a class name “typewriter”. Inside the division, we have a heading (h1) with the class name “typewriter-text”. The text within this heading is what will have the typewriter effect applied.

<html>
<head>
  <title>Typewriter Effect</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="typewriter">
    <h1 class="typewriter-text">Welcome to the Typewriter Effect!</h1>
  </div>
  <script src="script.js"></script>
</body>
</html>

Step 2: CSS Design

Our typewriter effect is accomplished using CSS. Here’s the CSS code responsible for the effect:

.typewriter {
  text-align: center;
  margin-top: 200px;
}

.typewriter-text {
  overflow: hidden; /* Hide overflowing characters */
  border-right: 2px solid black; /* Simulate cursor */
  white-space: nowrap; /* Prevent line breaks */
  margin: 0 auto; /* Center horizontally */
  letter-spacing: 2px; /* Adjust letter spacing as desired */
  animation: typing 5s steps(40) infinite;
}

@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 40%;
  }
}

Here’s a breakdown of the CSS classes:

  • .typewriter: This class centers the text and moves it down the page.
  • .typewriter-text: This class hides overflow text (with overflow: hidden;) to ensure that all text appears from the invisible border on the right. It also prevents line breaks (with white-space: nowrap;) and centers the text horizontally. The border on the right of the text box (with border-right: 2px solid black;) simulates the cursor.

The magic happens with the CSS animation property. The animation lasts for 5 seconds, and we are telling it to take 40 steps. This means the typewriter effect will print out one character every 1/8th of a second.

The @keyframes typing block specifies what the animation does during its duration. It gradually increases the width of the text container from 0 to 40% of its total width, giving the illusion that the text is being typed.

Conclusion

This tutorial showcased how HTML and CSS can work in unison to create a captivating typewriter text display effect. This effect can make your website stand out, offering your visitors a dynamic visual experience. With creativity and these code manipulations at your disposal, you can craft engaging and innovative web design effects.

Next up

Table of Contents