<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>css3无缝滚动</title>
</head>
<style id="test">
.scroll-container {
width: 300px;
height: 100px;
overflow: hidden;
margin: 50px auto;
position: relative;
}
.scroll-content {
position: absolute;
top: 0;
left: 0;
animation: scroll 10s linear infinite;
}
.scroll-content p {
margin: 0;
padding: 10px 0;
}
@keyframes scroll {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-50%);
}
}
</style>
<body>
<div class="scroll-container">
<div class="scroll-content">
<p>这是第一行字幕</p>
<p>这是第二行字幕</p>
<p>这是第三行字幕</p>
<p>这是第四行字幕</p>
<p>这是第一行字幕</p>
<p>这是第二行字幕</p>
<p>这是第三行字幕</p>
<p>这是第四行字幕</p>
</div>
</div>
</body>
</html>
- HTML 结构:
- 创建一个
scroll-container
容器,用于限制字幕滚动的区域。 - 在
scroll-container
内部,有一个scroll-content
容器,它包含了所有需要滚动的字幕<p>
元素。为了实现无缝滚动,将字幕内容重复一次。
- CSS 样式:
scroll-container
设置了固定的宽度和高度,并使用overflow: hidden
来隐藏超出容器范围的内容。margin: 50px auto
使容器在页面中水平居中且有一定的上边距。scroll-content
使用绝对定位,初始位置在容器的顶部。通过animation
属性应用名为scroll
的动画,持续时间为 10 秒,线性运动且无限循环。- 每个
<p>
元素设置了一定的内边距,用于调整字幕之间的垂直间距。
- 动画关键帧:
@keyframes scroll
定义了动画的关键帧。在 0% 处,字幕内容的初始位置为translateY(0)
,即没有垂直偏移。- 在 100% 处,字幕内容向上偏移了自身高度的 50%(因为字幕内容重复了一次,所以偏移 50% 刚好实现无缝衔接),即
translateY(-50%)
,从而实现了自下往上的连续无缝滚动效果。