专业编程基础技术教程

网站首页 > 基础教程 正文

纯CSS写出一只活泼乱跳的小白兔,非常简单,看了就会

ccvgpt 2024-08-03 12:39:02 基础教程 10 ℃

同样先放最终效果图:

动图演示:

纯CSS写出一只活泼乱跳的小白兔,非常简单,看了就会

一边听歌一边截的动图,所以图片下面有歌词闪过,大家忽视就好。

整个图像其实可以分为三个部分,一是蓝黑色的背景,二是三朵若隐若现的白云,三是这只往前跳的小兔子,背景可以直接在body里设置,因此我们的HTML主题部分就只需要下面两个div:

<div class="rabbit"></div>
<div class="clouds"></div>

接着CSS里开始设置样式,先是整体的背景:

body {
 margin: 0;
 height: 100vh;
 display: flex;
 align-items: center;
 justify-content: center;
 background: linear-gradient(midnightblue, black);
 font-size: 20px;
 margin-top: 2em;
 overflow: hidden;
}

引申一点相关知识:上面的CSS代码里display:flex其实是弹性布局,采用Flex布局的元素,称为Flex容器(flex container),简称”容器”。它的所有子元素自动成为容器成员,称为Flex项目(flex item),简称”项目”。

flex布局有以下6个属性:

  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content

其中,我们的代码里面用到的justify-content:center定义了项目在主轴上的对齐方式为center。

接下来设置小白兔:

.rabbit {
 width: 5em;
 height: 3em;
 color: whitesmoke;
 background: 
 radial-gradient(
 circle at 4.2em 1.4em,
 #333 0.15em,
 transparent 0.15em
 ), /* eye */
 currentColor;
 border-radius: 70% 90% 60% 50%;
 box-shadow: -0.2em 1em 0 -0.75em #333;
 z-index: 1;
 animation: hop 1s linear infinite;
}

大体都是一些基础的设置,这里着重介绍一下 animation: hop 1s linear infinite;这句。

animation是CSS3里的一个动画设置,使用上面的代码,将把 animation 绑定到一个hop这个div元素,因此我们需要写一个hop来实现小白兔前后跳动的动画:

@keyframes hop {
 20% {
 transform: rotate(-10deg) translate(1em, -2em);
 box-shadow: -0.2em 3em 0 -1em #333;
 }
 40% {
 transform: rotate(10deg) translate(3em, -4em);
 box-shadow: -0.2em 3.25em 0 -1.1em #333;
 }
 60%, 75% {
 transform: rotate(0deg) translate(4em, 0);
 box-shadow: -0.2em 1em 0 -0.75em #333;
 }
}

就这样,我们得到了一个光头往前跳动的小白兔:

其实还挺可爱的~

下面我们给小兔子加上耳朵:

.rabbit::before {
 content: '';
 position: absolute;
 width: 0.75em;
 height: 2em;
 background-color: currentColor;
 border-radius: 50% 100% 0 0;
 transform: rotate(-30deg);
 top: -1em;
 right: 1em;
 border: 0.1em solid;
 border-color: gainsboro transparent transparent gainsboro;
 box-shadow: -0.5em 0 0 -0.1em;
 }

加上耳朵后如下:

加上尾巴和影子:

.rabbit::after {
 content: '';
 position: absolute;
 width: 1em;
 height: 1em;
 background-color: currentColor;
 border-radius: 50%;
 left: -0.3em;
 top: 0.5em;
 box-shadow:
 0.5em 1em 0,
 4em 1em 0 -0.2em,
 4em 1em 0 -0.2em;
 animation: kick 1s infinite linear;
}

最后,给小白兔加上四周的白云:

.clouds {
 width: 2em;
 height: 2em;
 color: whitesmoke;
 background: currentColor;
 border-radius: 100% 100% 0 0;
 transform: translate(0, -5em);
 animation: cloudy 1s infinite linear forwards;
 filter: opacity(0);
}

云的动画以及细节调整这里就不在赘述了,再来看一张最终效果图:

今天的小练习就到这里啦。

需要完整代码的朋友可以留言或私信我获取。

最近发表
标签列表