2019-03-31 | UNLOCK

冰棍

今天给大家分享一下如何用纯 CSS 创作一支诱人的冰棍,效果图如下:

ice

首先定义 dom,容器中包含 2 个元素:

1
2
3
4
<div class="ice-lolly">
<div class="flavors"></div>
<div class="stick"></div>
</div>

样式居中显示:

1
2
3
4
5
6
7
8
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: darkslategray;
}

接着绘制出冰棍的外形,并给冰棍上色:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
.flavors {
position: relative;
overflow: hidden;
width: 19em;
height: 26em;
font-size: 10px;
border-radius: 8em 8em 1em 1em;
}
.flavors::before {
content: '';
position: absolute;
width: 140%;
height: 120%;
background: linear-gradient(
hotpink 0%,
hotpink 25%,
deepskyblue 25%,
deepskyblue 50%,
gold 50%,
gold 75%,
lightgreen 75%,
lightgreen 100%);
z-index: -1;
left: -20%;
transform: rotate(-25deg);
}

来一点光照效果:

1
2
3
4
5
6
7
8
9
10
.flavors::after {
content: '';
position: absolute;
width: 2em;
height: 17em;
background-color: rgba(255, 255, 255, 0.5);
left: 2em;
bottom: 2em;
border-radius: 1em;
}

画出冰棍筷子,并给冰棍筷子加一点阴影,增加立体感:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.stick {
position: relative;
width: 6em;
height: 8em;
background-color: sandybrown;
left: calc(50% - 6em / 2);
border-radius: 0 0 3em 3em;
}
.stick::after {
content: '';
position: absolute;
width: inherit;
height: 2.5em;
background-color: sienna;
}

让冰棍的色彩滚动起来:

1
2
3
4
5
6
7
8
.flavors::before {
animation: moving 100s linear infinite;
}
@keyframes moving {
to {
background-position: 0 1000vh;
}
}

最后,增加交互效果,当鼠标悬停时才播放动画:

1
2
3
4
5
6
.flavors::before {
animation-play-state: paused;
}
.ice-lolly:hover .flavors::before {
animation-play-state: running;
}

大功告成了!当然你可以在这里看到源码。

(完)

css

评论加载中