css基础必练之跑马灯

327 阅读1分钟

通过css动画实现一个跑马灯效果,样式如下:

走马灯.gif

1.新建一个ul,内置6个li,给每个li增加不同的背景颜色

<ul>
            <li style="background-color: #E9D7DF;"></li>
            <li style="background-color: #C08EAF;"></li>
            <li style="background-color: #C06F98;"></li>
            <li style="background-color: #5D3F51;"></li>
            <li style="background-color: #36292F;"></li>
            <li style="background-color: #38242d;"></li>

</ul>

2.给ul一个设置样式,子绝父相,定位居中

      * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            list-style: none;
        }
        ul {
            width: 400px;
            height: 400px;
            margin: 200px auto;
            position: relative;
            /* 创建3d空间 */
            transform-style: preserve-3d;
            /* 沿x轴旋转5度 */
            transform: rotateX(-5deg);
            /* 设置动画 */
            animation: move 10s infinite linear;
        }

3.定义动画

@keyframes move {
            to {
                transform: rotateX(-5deg) rotateY(360deg);
            }
        }

4.给li设置样式

li {
            position: absolute;
            width: 300px;
            height: 200px;
            top: 0;
            left: 0;
        }

5.给每一个li设置transform

li:nth-child(1) {
            transform: translateZ(600px);
        }

        li:nth-child(2) {
            transform: translateZ(-600px) rotateY(180deg);
        }

        li:nth-child(3) {
            transform: rotateY(60deg) translateZ(-600px);
        }

        li:nth-child(4) {
            transform: rotateY(60deg) translateZ(600px);
        }

        li:nth-child(5) {
            transform: rotateY(-60deg) translateZ(-600px);
        }

        li:nth-child(6) {
            transform: rotateY(-60deg) translateZ(600px);
        }

6.最后给ul设置一个经过暂停

ul:hover {
        /* 经过暂停 */
            animation-play-state: paused;
        }

可以直接在li里面放图片,记得给图片设置相同宽高

li>img{
            width: 300px;
            height: 200px;
        }

效果如下,图源网络

效果.gif