纯html+css实现打字效果
当然可以,以下是如何使用纯 HTML 和 CSS 实现打字效果的示例:
HTML:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typewriter Effect</title>
<style>
/* Basic styles */
body {
margin: 0;
padding: 0;
font-family: monospace;
background-color: #f0f0f0;
}
/* Container for the text */
.text-container {
position: relative;
width: fit-content;
margin: 0 auto;
padding: 20px;
background-color: #fff;
}
/* The text that will be animated */
.text {
overflow: hidden;
white-space: nowrap;
animation: typing 2s steps(20) forwards;
}
/* Cursor animation */
.cursor {
position: absolute;
bottom: 0;
right: 0;
width: 2px;
height: 20px;
background-color: #333;
animation: blink 0.5s steps(1) infinite;
}
/* CSS animations */
@keyframes typing {
from {
width: 0;
}
to {
width: 100%;
}
}
@keyframes blink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
</style>
</head>
<body>
<div class="text-container">
<span class="text">This is a sample text that will appear with a typewriter effect.</span>
<div class="cursor"></div>
</div>
</body>
</html>
Explanation:
HTML Structure:
div
container with the class text-container
to hold the animated text.span
with the class text
contains the text that will be animated.div
with the class cursor
is added after the text to create the blinking cursor effect.CSS Styles:
.text-container
is styled with padding and background color..text
is set to overflow: hidden
to prevent the text from wrapping, and white-space: nowrap
to keep spaces from collapsing. The typing
animation is applied to make the text appear gradually..cursor
is positioned absolutely at the bottom right, styled with a background color, and given a blinking animation using blink
.Key CSS Properties:
animation: typing 2s steps(20) forwards
: Defines the typing animation with a duration of 2 seconds, 20 steps (each revealing a character), and forwards playback.animation: blink 0.5s steps(1) infinite
: Defines the blinking cursor animation with a duration of 0.5 seconds, 1 step (toggling opacity), and infinite repetition.overflow: hidden
, white-space: nowrap
: Control the text appearance during animation.position: absolute
, background-color
: Style the cursor appearance.Customizations: