根據五環的位置特點,可以將中間的黑色環設定為 HTML 的父元素,而將其他顏色的環設定為子元素。這樣,其他環就可以相對於黑色環進行定位。整體的 HTML 結構如下:
<div class="black"> <div class="ring blue"></div> <div class="ring yellow"></div> <div class="ring green"></div> <div class="ring red"></div> </div>
首先,用 CSS 邊框畫出黑環和其他四環的基本樣式:
.black { position: relative; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; } .ring { position: absolute; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; top: -20px; right: -20px; }
接下來畫綠環,它相對於黑環進行定位,向右向下移動,並且層級比黑環高:
.green { color: #30a751; top: 70px; right: -125px; z-index: 2; }
此時的效果是這樣的,黑環的z-index
為 1,綠環的z-index
為 2:
而我們希望兩環右側的交車點處,黑環位於上方,這時就可以使用偽元素來實現。給黑環新增一個和它大小一樣的偽元素::after
,並將其放在黑環的正上方,z-index
為3
。接著,將偽元素的右邊框設定為黑色,其他方向為透明,這樣就成功使黑環的右側看起來位於綠環上方了:
.black { position: relative; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; &::after { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 100%; top: -20px; right: -20px; border: 20px solid transparent; border-right: 20px solid currentcolor; z-index: 3; } }
這裡我來向右移動一下這個偽元素的位置,來看看他的樣子:
到這你應該就明白了,這裡只是視覺上的環環相扣,實際上,兩個環並不在同一層。
接下來畫紅環。由於綠環的z-index
為2
,所以紅環位於綠環下方:
.red { color: #ef314e; right: -230px; }
.red { color: #ef314e; right: -230px; &::after { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; top: -20px; right: -20px; border: solid 20px transparent; border-bottom: solid 20px currentcolor; z-index: 2; } }
整體程式碼如下:
.black { position: relative; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; &::after { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 100%; top: -20px; right: -20px; border: 20px solid transparent; border-right: 20px solid currentcolor; z-index: 3; } &::before { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 100%; top: -20px; right: -20px; border: 20px solid transparent; border-bottom: 20px solid currentcolor; z-index: 1; } .ring { position: absolute; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; top: -20px; right: -20px; } .green { color: #30a751; top: 70px; right: -125px; z-index: 2; } .red { color: #ef314e; right: -230px; &::after { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; top: -20px; right: -20px; border: solid 20px transparent; border-bottom: solid 20px currentcolor; z-index: 2; } } .yellow { color: #fcb32e; top: 70px; left: -125px; } .blue { color: #0082c9; left: -230px; &::after { content: ""; position: absolute; width: 200px; height: 200px; border-radius: 50%; border-width: 20px; border-style: solid; top: -20px; right: -20px; border: solid 20px transparent; border-right: solid 20px currentcolor; z-index: 2; } } }
最終效果如下:
感謝閱讀,記著點個贊哦,在此,謝謝各位啦!!!