探秘 CSS:如何让气泡在盒子里灵动起舞

239 阅读2分钟

这段代码创建了一个具有动态气泡效果的盒子,通过 CSS 技术实现了气泡的上下浮动效果,为页面添加了视觉吸引力和动态感。

演示效果

HTML&CSS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>公众号关注:前端Hardy</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }

        @keyframes drop {
            0% {
                transform: translateY(0px);
            }

            50% {
                transform: translateY(80px);
            }

            100% {
                transform: translateY(0px);
            }
        }

        .box {
            position: relative;
            width: 50px;
            height: 100px;
            background: #000;
            border-radius: 25px;
            overflow: hidden;
        }

        .b1 {
            position: absolute;
            top: 0;
            width: 20px;
            height: 20px;
            background: linear-gradient(to bottom, #e64980, #ff8787);
            border-radius: 50%;
            left: 15px;
            animation: drop 5s ease-in-out infinite;
        }

        .b2 {
            position: absolute;
            top: 0;
            width: 20px;
            height: 20px;
            background: linear-gradient(to bottom, #82c91e, #3bc9db);
            border-radius: 50%;
            left: 1px;
            animation: drop 3s ease-in-out infinite;
        }

        .b3 {
            position: absolute;
            top: 0;
            width: 20px;
            height: 20px;
            background: linear-gradient(to bottom, #7950f2, #f783ac);
            border-radius: 50%;
            left: 30px;
            animation: drop 4s ease-in-out infinite;
        }

        .b4 {
            position: absolute;
            top: 0;
            width: 20px;
            height: 20px;
            background: linear-gradient(to bottom, #4481eb, #04befe);
            border-radius: 50%;
            left: 20px;
            animation: drop 6s ease-in-out infinite;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="b1"></div>
        <div class="b2"></div>
        <div class="b3"></div>
        <div class="b4"></div>
    </div>

</body>

</html>

HTML 结构

  • box: 创建一个类名为 box 的 div 元素,用于包含气泡。
  • b1、b2、b3、b4:创建气泡。

CSS 样式

  • body: 设置页面的边距、填充、背景色、显示方式和高度。
  • @keyframes drop: 定义一个名为“drop”的关键帧动画,用于实现气泡的上下浮动效果。0%: 气泡的初始位置。50%: 气泡向下移动 80 像素。100%: 气泡回到初始位置。
  • .box: 设置盒子的样式,包括尺寸、背景色、边框半径和溢出隐藏。
  • .b1, .b2, .b3, .b4: 设置气泡的样式,包括尺寸、背景渐变、边框半径和位置。
  • animation: drop ...: 应用“drop”动画,设置动画的持续时间、缓动函数和循环方式。