円や三角形など、シンプルな図形をCSSで作るときがたまにあるのですが、同じ形の図形を複数作りたいときの方法を見つけたのでメモしておきます。
サンプルコード1
まずは、図形の数だけ要素を追加してみます。
HTML
<div class="circle"> <span class="circle01"></span> <span class="circle02"></span> <span class="circle03"></span> <span class="circle04"></span> <span class="circle05"></span> </div>
CSS
.circle {
position: relative;
width: 300px;
height: 40px;
background: #eee;
}
.circle span {
position: absolute;
top: 10px;
width: 20px;
height: 20px;
border-radius: 10px;
background: #333;
}
.circle01 {
left: 60px;
}
.circle02 {
left: 100px;
}
.circle03 {
left: 140px;
}
.circle04 {
left: 180px;
}
.circle05 {
left: 220px;
}
図形の数だけ要素を追加するデモページ
これでも実装はできますが、不要なタグが追加されてしまいます。
サンプルコード2
box-shadowはカンマ区切りで複数指定できるので、これで図形を複数作成してみます。
HTML
<div class="circle"></div>
CSS
.circle {
position: relative;
width: 300px;
height: 40px;
background: #eee;
}
.circle:before {
content: '';
position: absolute;
top: 10px;
width: 20px;
height: 20px;
border-radius: 10px;
background: red;
box-shadow: 60px 0 0 #333, 100px 0 0 #333, 140px 0 0 #333, 180px 0 0 #333, 220px 0 0 #333;
}
box-shadowで図形を複数作成するデモページ
赤丸が本来の要素で、黒丸がbox-shadowで作成した図形になります。
1,2番目の値で水平・垂直位置を指定して、3番目の値を0にしてぼかさないようにします。
注意点としては、本来の要素がある位置では表示できない(要素の下にbox-shadowがくるので表示されない)ので、図形を配置したい位置から要素をずらしておく必要があります。
【参考サイト】
コメントが承認されるまで時間がかかります。