使用CSS为直线运动中的直线设置动画

HTML:在HTML中,我们创建了一个div元素,用于制作一条直线。

<!DOCTYPE html> <html lang="en">
<head>     <meta charset="UTF-8" />     <meta name="viewport" content=         "width=device-width, initial-scale=1.0" />     <title>GeeksforGeeks</title> </head>
<body>     <div class="geeks"></div> </body>
</html>

CSS:

  • 通过提供您喜欢的最小高度和宽度来创建一条直线。

  • 使用before选择器对此直线进行动画处理,并为其提供线性动画,并带有名为animate的关键帧标识符。

  • 关键帧的动画非常简单。对于前半帧,使宽度为100%(向前移动),然后将其减小为下半帧的0%(向后移动)。

<style>     body {         margin: 0;         padding: 0;         background: green;     }
    .geeks {         width: 400px;         height: 2px;         background: #fff;         position: absolute;         top: 50%;         left: 50%;         transform: translate(-50%, -50%);     }
    .geeks::before {         content: "";         position: absolute;         top: 0;         left: 0;         width: 100%;         height: 100%;         background: green;         animation: animate 5s linear infinite;     }
    @keyframes animate {         0% {             left: 0;         }
        50% {             left: 100%;         }
        0% {             left: 0;         }     } </style>

完整代码:在本节中,我们将结合使用HTML和CSS代码来制作直线动画效果。

<!DOCTYPE html> <html lang="en">
<head>     <meta charset="UTF-8" />     <meta name="viewport" content=         "width=device-width, initial-scale=1.0" />
    <title>         How to animate a straight         line in linear motion?     </title>
    <style>         body {             margin: 0;             padding: 0;             background: green;         }
        .geeks {             width: 400px;             height: 2px;             background: #fff;             position: absolute;             top: 50%;             left: 50%;             transform: translate(-50%, -50%);         }
        .geeks::before {             content: "";             position: absolute;             top: 0;             left: 0;             width: 100%;             height: 100%;             background: green;             animation: animate 5s linear infinite;         }
        @keyframes animate {             0% {                 left: 0;             }
            50% {                 left: 100%;             }
            0% {                 left: 0;             }         } </style> </head>
<body>     <div class="geeks"></div> </body>
</html>
原文地址:https://www.cnblogs.com/xiewangfei123/p/13150361.html