生活中,我们早上通常都会吃一个茶叶蛋来补充一天的营养,今天我们就来用CSS来实现一个可爱蛋吧
效果图
实现思路
我们利用container类名盒子作为可爱蛋的载体并通过flex布局的方式使得可爱蛋能够在元素中居中,给上地位便于以后进行定位操作,在通过外边距使得载体距离上面有一定的距离,我们来用ellipse盒子用于定位蛋身里面的内容以及实现单身下边部分的黄壳,egg类名盒子作为蛋身,通过边框圆角的属性实现椭圆蛋身,在通过eye类名元素通过定位结合伪元素的方式实现眼睛的布局,在通过mouth类名元素实现嘴巴的效果,在通过无序列表的方式实现一个蛋齿纹,最后通过动画属性实现可爱蛋的摇摆,下面我们来实现一下吧
主体结构
<div class="container">
<!-- 蛋 -->
<div class="ellipse">
<!-- 内容 -->
<div class="egg">
<!-- 蛋眼睛 -->
<div class="eye"></div>
<div class="eye"></div>
<!-- 蛋嘴巴 -->
<div class="mouth"></div>
<!-- 蛋齿纹 -->
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
初始样式
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
}
可爱蛋的载体,在通过圆边框属性实现单身的椭圆形状
.container {
width: 500px;
height: 500px;
margin: 50px auto;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.ellipse {
position: relative;
}
.egg {
width: 290px;
height: 340px;
border: 18px solid black;
border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
position: relative;
z-index: 5;
}
眼睛
我们在给可爱蛋做出眼睛,这里通过俩个盒子进行实现,一个左眼睛一个右眼睛,在通过伪元素的方式实现目光,在通过定位的方式定位到对应的位置
.eye {
position: absolute;
width: 30px;
height: 30px;
border-radius: 50%;
background-color: #000;
top: 18%
}
.eye:nth-child(1) {
left: 23%;
}
.eye:nth-child(2) {
right: 23%;
}
.eye::after {
content: "";
width: 13px;
height: 13px;
background-color: #fff;
border-radius: 50%;
position: absolute;
left: 2px;
top: 3px;
}
嘴巴
嘴巴这里我们通过css的定位方式以及旋转属性实现一个菱形的效果定位到合适的位置
.mouth {
width: 28px;
height: 28px;
background-color: #000;
border-radius: 12% / 4%;
transform: rotate(45deg) translateX(-50%);
transform-origin: left;
position: absolute;
top: 35%;
left: 50%;
}
齿纹
我们通过无序列表的方式结合定位以及旋转属性实现蛋壳齿纹,因为每个元素旋转的度数不一样,所以需要每一个都单独设置旋转角度
.egg ul li {
position: absolute;
height: 51px;
transform: rotate(220deg);
border-left: 18px solid black;
border-top: 18px solid black;
}
.egg ul li:nth-child(1) {
top: 53%;
height: 40px;
width: 45px;
left: -4px;
}
.egg ul li:nth-child(2) {
top: 49.5%;
width: 58px;
left: 16%;
}
.egg ul li:nth-child(3) {
top: 49.5%;
width: 58px;
left: 36.5%;
}
.egg ul li:nth-child(4) {
top: 49.5%;
width: 58px;
left: 57%;
}
.egg ul li:nth-child(5) {
top: 49.5%;
width: 62px;
left: 77.5%;
}
下半身
这样基本上做好了,不过下面的蛋壳齿纹下面不太好看,我们通过伪元素来做一个下半身蛋壳
.ellipse::after {
content: "";
position: absolute;
width: calc(100% - 25px);
height: 39%;
background-color: rgba(244, 247, 97, 0.753);
bottom: 0;
left: 10px;
border-radius: 0 0 50% 50% / 0 0 100% 100%;
z-index: 0;
}
动画
最后我们通过css的动画属性设置动画在0%/50%/100%的时候角度全部归为0也就是原本样式,在25%和75%的时候分别向右偏移10deg和向左偏移10deg,在给ellipse类名盒子设置好摇摆角度和对应的运行速度进行无限次运行
.ellipse {
animation: swing 3s linear infinite;
transform-origin: center bottom;
}
@keyframes swing {
0% {
transform: rotate(0deg);
}
25% {
transform: rotate(10deg);
}
50% {
transform: rotate(0deg);
}
75% {
transform: rotate(-10deg);
}
100% {
transform: rotate(0deg);
}
}
代码我已经放到码上掘金上了,快开看看吧!
我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!