我們最終要實現的效果如下:
你們相信嗎?這麼一個相對複雜的圖形只需要一個div就能夠實現。下面就跟我來學習如何實現。
1. 首先寫出代碼結構,只需要如下一行
<div class="mustache"></div>
2. 通過分析可以發現,這個鬍子是左右對稱的,因此只需要實現一邊的鬍子就可以了。
首先畫鬍子中間的圓
爲.mustache添加樣式
.mustache{
width: 100px;
height: 100px;
background: black;
border-radius: 50%;
}
3. 然後通過僞元素來爲鬍子添加鬍鬚
.mustache:before, .mustache:after{
content: '';
display: block;
position: absolute;
border-bottom: 1px solid;
transform-origin: right bottom;
border-radius: 0 0 0 100%;
}
.mustache:before{
width: 106px;
height: 100px;
background: white;
z-index: 2;
left: 125px;
top: -8px;
transform: rotate(-20deg);
}
.mustache:after{
width: 200px;
height: 100px;
left: 30px;
top: -7px;
background: black;
transform: rotate(-20deg);
}
4. 最後通過css3的倒影來畫另一邊的鬍子,也就是box-reflect,這個樣式接收兩個參數:第一個是倒影的方向,
第二個是倒影的位移。
完成了,是不是很神奇。
最終的代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>純css畫鬍子</title>
<style>
*{
margin: 0; padding: 0;
}
.mustache{
width: 100px;
height: 100px;
background: black;
border-radius: 50%;
transform: translate(220px);
-webkit-box-reflect: left -20px;
box-reflect: left -20px
}
.mustache:before, .mustache:after{
content: '';
display: block;
position: absolute;
border-bottom: 1px solid;
transform-origin: right bottom;
border-radius: 0 0 0 100%;
}
.mustache:before{
width: 106px;
height: 100px;
background: white;
z-index: 2;
left: 125px;
top: -8px;
transform: rotate(-20deg);
}
.mustache:after{
width: 200px;
height: 100px;
left: 30px;
top: -7px;
background: black;
transform: rotate(-20deg);
}
</style>
</head>
<body>
<div class="mustache"></div>
</body>
</html>