寫在前面的話:
在日常的工作中遇到一個需求,需要用圓柱體來表現每個項目的比例,首先想到的會事使用echarts中的柱狀圖來表現,但是為了一個圓柱體引用那么龐大的js庫有點不合時宜的味道。其次是想到使用canvas畫布工具里封裝一個小插件供系統使用,可是要百度啥的,目前俺還不是很能熟練使用canvas,而且考慮再三之后使用純css 是可以滿足目前的開發要求的。
正文:
首先定義結構:
點擊查看代碼
<div class="lui-column-bg">
<div class="lui-inner" style="height: 50%;">
</div>
</div>
.lui-column-bg 用來做父容器其中的.lui-inner 作為子容器其高度和父容器的高度的百分比作為 項目比。
其次是css,使用偽類元素before和after作為圓柱的上下底面。使用漸變的背景使得圓柱體更加立體一點。
點擊查看代碼
.lui-column-bg {
position: relative;
width: 50px;
height: 90px;
margin: 100px auto;
background-color: transparent;
background-color: rgba(0, 199, 159, 0.2);
}
.lui-column-bg:before {
position: absolute;
content: '';
display: block;
height: 20px;
width: 100%;
border-radius: 50%;
top: -10.5px;
z-index: 1;
background-color: rgb(101 221 197);
}
.lui-column-bg:after {
position: absolute;
content: '';
display: block;
height: 15px;
width: 100%;
border-radius: 50%;
bottom: -10px;
background-color: rgb(0, 255, 204);
}
.lui-inner {
position: absolute;
bottom: 0;
width: 100%;
height: 50%;
background-image: linear-gradient(to top, rgb(0, 255, 204), rgb(0, 199, 159));
text-align: center;
}
.lui-inner::before {
position: absolute;
content: '';
display: block;
height: 20px;
width: 100%;
background-color: rgb(0, 199, 159);
border-radius: 50%;
top: -10.5px;
z-index: 1;
}
.lui-inner:after {
position: absolute;
content: '';
display: block;
height: 15px;
width: 100%;
border-radius: 50%;
background-color: white;
bottom: -10px;
}
效果如下:
最后附上完整的代碼:
點擊查看代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css實現圓柱體</title>
<style>
.lui-column-bg {
position: relative;
width: 50px;
height: 90px;
margin: 100px auto;
background-color: transparent;
background-color: rgba(0, 199, 159, 0.2);
}
.lui-column-bg:before {
position: absolute;
content: '';
display: block;
height: 20px;
width: 100%;
border-radius: 50%;
top: -10.5px;
z-index: 1;
background-color: rgb(101 221 197);
}
.lui-column-bg:after {
position: absolute;
content: '';
display: block;
height: 15px;
width: 100%;
border-radius: 50%;
bottom: -10px;
background-color: rgb(0, 255, 204);
}
.lui-inner {
position: absolute;
bottom: 0;
width: 100%;
height: 50%;
background-image: linear-gradient(to top, rgb(0, 255, 204), rgb(0, 199, 159));
text-align: center;
}
.lui-inner::before {
position: absolute;
content: '';
display: block;
height: 20px;
width: 100%;
background-color: rgb(0, 199, 159);
border-radius: 50%;
top: -10.5px;
z-index: 1;
}
.lui-inner:after {
position: absolute;
content: '';
display: block;
height: 15px;
width: 100%;
border-radius: 50%;
background-color: white;
bottom: -10px;
}
</style>
</head>
<body>
<div class="lui-column-bg">
<div class="lui-inner" style="height: 50%;">
</div>
</div>
</body>
</html>