.bunny { position: relative; width: 100px; height: 140px; } .bunny .left-ear, .bunny .right-ear { position: absolute; top: -40px; width: 0; height: 0; border: 20px solid transparent; border-bottom: 40px solid white; border-radius: 25px 25px 0 0; transform-origin: center bottom; } .bunny .left-ear { left: 15px; transform: rotate(-45deg); } .bunny .right-ear { right: 15px; transform: rotate(45deg); } .bunny .face { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: white; border-radius: 50%; } .bunny .left-eye, .bunny .right-eye { position: absolute; top: 38%; width: 10px; height: 10px; background-color: black; border-radius: 50%; } .bunny .left-eye { left: 42%; } .bunny .right-eye { right: 42%; } .bunny .nose { position: absolute; top: 60%; left: 45%; width: 10px; height: 6px; background-color: pink; border-radius: 50%; } .bunny .mouth { position: absolute; top: 65%; left: 45%; width: 10px; height: 4px; background-color: black; border-radius: 50%; } .bunny.animate .left-ear { animation: bounce-ear-left 0.8s linear infinite alternate; } .bunny.animate .right-ear { animation: bounce-ear-right 0.8s linear infinite alternate; } @keyframes bounce-ear-left { 0%, 100% { transform: rotate(-45deg); } 50% { transform: rotate(-60deg); } } @keyframes bounce-ear-right { 0%, 100% { transform: rotate(45deg); } 50% { transform: rotate(60deg); } }
代码中,大家定义了一个 .bunny 类,包括兔子的两个耳朵、脸、眼睛、鼻子和嘴巴等。其中,.left-ear 和 .right-ear 的样式中加入了动画 animation 属性,分别实现了左耳和右耳的抖动效果。
同时,运用 CSS3 中的 transform 来实现旋转,逐帧逐步降低左右耳朵的旋转角度。通过 CSS 动画起来,可以看到一个可爱的兔子在屏幕上跳跃。