使用position: relative和@keyframes可实现元素偏移动画。先设置position: relative使元素保持布局稳定,再通过@keyframes定义动画关键帧,推荐使用transform: translateX()实现位移以提升性能,最后将动画绑定到元素上,设置动画名称、持续时间、速度曲线和重复次数等参数。例如让一个蓝色方块在原位置左右来回滑动,只需设置animation: slideRight 2s ease infinite alternate,其中slideRight定义从translateX(0)到translateX(150px)的位移变化。整个过程流畅且不影响页面布局。

使用 CSS 的 position: relative 与 @keyframes animation 可以轻松实现元素的偏移动画。关键在于通过相对定位控制元素在原有位置上的偏移,并结合动画规则让偏移量随时间变化。
要让元素能相对于自己原本的位置移动,先设置 position: relative。这样不会影响页面布局,同时允许你使用 top, right, bottom, left 来调整位置。
.moving-element {
position: relative;
}
使用 @keyframes 定义动画的关键帧。比如从左边移动到右边,可以通过改变 left 或 transform: translateX() 实现。
@keyframes slideRight {
from {
left: 0;
}
to {
left: 200px;
}
}
或者更推荐使用 transform,性能更好:
立即学习“前端免费学习笔记(深入)”;
@keyframes slideRight {
from {
transform: translateX(0);
}
to {
transform: translateX(200px);
}
}
将定义好的动画绑定到元素上,设置持续时间、重复次数等参数。
.moving-element {
position: relative;
animation: slideRight 2s ease-in-out infinite;
}
说明:
<div class="box">我会移动</div>
<style>
.box {
width: 100px;
height: 100px;
background: blue;
color: white;
text-align: center;
line-height: 100px;
position: relative;
animation: slideRight 2s ease infinite alternate;
}
@keyframes slideRight {
0% {
transform: translateX(0);
}
100% {
transform: translateX(150px);
}
}
</style>
这个例子中,蓝色方块会在原位置左右来回滑动。
基本上就这些。用 relative 保持布局稳定,再配合 animation 控制偏移,就能做出流畅的移动效果。注意优先使用 transform 而非 left/right,性能更优。以上就是如何用css relative与animation结合制作偏移动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号