使用CSS3实现空中飘动的云朵动画

442 阅读2分钟

"```markdown

使用CSS3实现空中飘动的云朵动画

在Web开发中,动画效果可以让页面更加生动。本文将介绍如何使用CSS3创建一个简单的空中飘动的云朵动画。

HTML结构

首先,我们需要创建一个基本的HTML结构,用于容纳云朵。

<!DOCTYPE html>
<html lang=\"zh\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>云朵动画</title>
    <link rel=\"stylesheet\" href=\"styles.css\">
</head>
<body>
    <div class=\"cloud\"></div>
    <div class=\"cloud\"></div>
    <div class=\"cloud\"></div>
</body>
</html>

CSS样式

接下来,我们为云朵添加样式,并实现动画效果。

body {
    background: #87CEEB; /* 天空蓝背景 */
    overflow: hidden; /* 隐藏溢出 */
    margin: 0;
    height: 100vh; /* 视口高度 */
}

.cloud {
    background: white; /* 云朵颜色 */
    border-radius: 50%; /* 圆形边框 */
    position: absolute; /* 绝对定位 */
    opacity: 0.8; /* 透明度 */
}

.cloud::before,
.cloud::after {
    content: '';
    background: white;
    border-radius: 50%;
    position: absolute;
}

.cloud {
    width: 100px; /* 云朵宽度 */
    height: 60px; /* 云朵高度 */
}

.cloud::before {
    width: 60px; /* 伪元素宽度 */
    height: 60px; /* 伪元素高度 */
    top: -30px; /* 伪元素上移 */
    left: 20px; /* 伪元素左移 */
}

.cloud::after {
    width: 80px; /* 伪元素宽度 */
    height: 80px; /* 伪元素高度 */
    top: -40px; /* 伪元素上移 */
    right: 20px; /* 伪元素右移 */
}

/* 动画效果 */
@keyframes float {
    0% {
        transform: translateX(0);
    }
    50% {
        transform: translateX(20px);
    }
    100% {
        transform: translateX(0);
    }
}

/* 云朵动画 */
.cloud {
    animation: float 5s ease-in-out infinite; /* 5秒循环动画 */
}

.cloud:nth-child(1) {
    top: 20%; /* 第一个云朵位置 */
    left: -10%; /* 第一个云朵初始位置 */
    animation-duration: 6s; /* 动画持续时间 */
}

.cloud:nth-child(2) {
    top: 40%; /* 第二个云朵位置 */
    left: -15%; /* 第二个云朵初始位置 */
    animation-duration: 7s; /* 动画持续时间 */
}

.cloud:nth-child(3) {
    top: 60%; /* 第三个云朵位置 */
    left: -20%; /* 第三个云朵初始位置 */
    animation-duration: 8s; /* 动画持续时间 */
}

解释

  1. HTML结构:创建了三个<div>元素,代表云朵。
  2. CSS样式
    • 使用background属性设置云朵的颜色,使用border-radius使其呈现圆形。
    • 通过伪元素::before::after,使云朵看起来更蓬松。
    • 使用@keyframes定义浮动动画,通过translateX实现左右移动的效果。
  3. 动画效果:通过animation属性将浮动效果应用到云朵上,并为每个云朵设置不同的动画持续时间,使其看起来自然。

结果

通过以上代码,可以在浏览器中看到白色云朵在蓝天中缓缓飘动的效果。这种简单的CSS3动画可以为网页添加生动的元素,提升用户的视觉体验。