HTML5+CSS3小实例:有趣的沙漏加载动画

1,019 阅读2分钟

HTML5+CSS3做一个有趣的沙漏加载动画,如此精致的沙漏,如果我说这个没有用到图片,纯CSS实现,你信吗?这个loading虽然看起来简单,但是你仔细拆解一番,你会发现其中居然用了四个动画,所以这个实例可以有效的锻炼大家的CSS动画。

效果:

源码:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">

    <title>纯CSS实现沙漏加载动画</title>
    <link rel="stylesheet" href="../css/19.css">
</head>

<body>
    <div class="loading">
        <span class="top"></span>
        <span class="bottom"></span>
    </div>
</body>

</html>
body{
    /* 取消页面内外边距 */
    margin: 0;
    padding: 0;
    /* 100%窗口高度 */
    height: 100vh;
    /* 弹性布局 水平、垂直居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    /* 渐变背景 */
    background: linear-gradient(200deg,#b5aee4,#505285);
}
.loading{
    width: 86px;
    height: 196px;
    /* 相对定位 */
    position: relative;
    /* 弹性布局 */
    display: flex;
    /* 将元素垂直显示 */
    flex-direction: column;
    /* 将元素靠边对齐 */
    justify-content: space-between;
    align-items: center;
    /* 执行动画:动画 时长 线性的 无限次播放 */
    animation: rotating 2s linear infinite;
}
/* 添加流下的元素 */
.loading::after{
    content: "";
    width: 5px;
    height: 96px;
    background-color: #cabbe9;
    /* 绝对定位 */
    position: absolute;
    top: 20px;
    /* 执行动画 */
    animation: flow 2s linear infinite;
}
/* 沙漏上下两个容器 */
.top,.bottom{
    width: 70px;
    height: 70px;
    border-style: solid;
    border-color: #dcdcdc;
    border-width: 4px 4px 12px 12px;
    border-radius: 50% 100% 50% 30%;
    position: relative;
    overflow: hidden;
}
.top{
    /* 旋转-45度 */
    transform: rotate(-45deg);
}
.bottom{
    /* 旋转135度 */
    transform: rotate(135deg);
}
.top::before,
.bottom::before{
    content: "";
    /* 绝对定位 */
    position: absolute;
    /* inherit表示继承父元素(这里指宽高) */
    width: inherit;
    height: inherit;
    background-color: #cabbe9;
    /* 执行动画,先设置动画的参数,不指定动画名称 */
    animation: 2s linear infinite;
}
.top::before{
    /* 通过设置圆角改变沙的形状 */
    border-radius: 0 100% 0 0;
    /* 指定执行的动画 */
    animation-name: drop-sand;
}
.bottom::before{
    /* 通过设置圆角改变沙的形状 */
    border-radius: 0 0 0 25%;
    /* 指定执行的动画 */
    animation-name: fill-sand;
    /* 把下面的沙移出可视范围 */
    transform: translate(50px,-50px);
}

/* 定义动画 */
/* 落沙动画 */
@keyframes drop-sand{
    to{
        transform: translate(-50px,50px);
    }
}
/* 填沙动画 */
@keyframes fill-sand{
    to{
        transform: translate(0,0);
    }
}
/* 沙流下动画 */
@keyframes flow{
    10%,100%{
        transform: translateY(64px);
    }
}
/* 沙漏旋转动画 */
@keyframes rotating{
    0%,90%{
        transform: rotate(0deg);
    }
    100%{
        transform: rotate(180deg);
    }
}