CSS|円形のパスの上に等間隔に円形のボタンを配置する
要素を円形に添って配置する図を作成する場合、画像で作成されている場合も多いのだけれど、要素が増える度に位置を調整して画像を作り直すのも大変だったので、CSSを使用して円形のパスに添ってボタンを等間隔に配置した方法をメモ。 HTML <div class="circle-wrapper"> <div class="circle-button" style="--i: 0;">1</div> <div class="circle-button" style="--i: 1;">2</div> <div class="circle-button" style="--i: 2;">3</div> <div class="circle-button" style="--i: 3;">4</div> <div class="circle-button" style="--i: 4;">5</div> <div class="circle-button" style="--i: 5;">6</div> <div class="circle-button" style="--i: 6;">7</div> <div class="circle-button" style="--i: 7;">8</div> <div class="circle-button" style="--i: 8;">9</div> <div class="circle-button" style="--i: 9;">10</div> <div class="circle-button" style="--i: 10;">11</div> <div class="circle-button" style="--i: 11;">12</div> </div> CSS .circle-wrapper { position: relative; width: 300px; height: 300px; margin: 50px auto; border: 2px dashed #ccc; border-radius: 50%; } .circle-button { --count: 12; /* 合計の個数 */ --radius: 130px; /* 円の半径 - ボタン半径 */ position: absolute; top: 50%; left: 50%; width: 40px; height: 40px; background: #3498db; border-radius: 50%; transform: rotate(calc(360deg / var(--count) * var(--i))) translate(var(--radius)) rotate(calc(-360deg / var(--count) * var(--i))); transform-origin: center; margin: -20px 0 0 -20px; /* ボタンの中心を基準にする */ text-align: center; line-height: 40px; } HTMLに記載されている「style="--i: 0;"」はカスタムプロパティ(CSS変数)の設定。タグごとに設定し直すことで「transform」の値を変更しボタンの順序に応じて角度をずらして配置しています。「--radius」の値は外側の円に内接するよう外側の円の半径からボタンの半径を差し引いた値を設定。外側の円に外接する場合は外側の円の半径にボタンの半径を加えた値(例は170px)になります。 サンプル .circle-wrapper { position: relative; width: 300px; height: 300px; margin: 50px auto; border: 2px dashed #ccc; border-radius: 50%; } .circle-button { --count: 12; --radius: 130px; position: absolute; top: 50%; left: 50%; width: 40px; height: 40px; background: #3498db; border-radius: 50%; transform: rotate(calc(360deg / var(--count) * var(--i))) translate(var(--radius)) rotate(calc(-360deg / var(--count) * var(--i))); transform-origin: center; margin: -20px 0 0 -20px !important; text-align: center; line-height: 40px; } 1 2 3 4 5 6 7 8 9 10 11 12






