How to place images around a circle
Using offset
combined with the new sibling-index()
and sibling-count()
functions, we can easily and precisely place images (or any elements) around a circle using a few lines of code.
.container {
display: inline-grid;
}
.container img {
--s: 150px; /* image size */
--g: 10px; /* control the gap */
width: var(--s);
grid-area: 1/1;
offset:
circle(calc(var(--s)/(2*sin(.5turn/sibling-count())) + var(--g)))
calc(100%*sibling-index()/sibling-count()) 0deg;
}
Add/remove images in the demo below, and see how they are perfectly placed regardless of their number.
See the Pen Images around a circle by Temani Afif (@t_afif) on CodePen.
If you don't want to be precise, you can simplify the code like below
.container {
display: inline-grid;
}
.container img {
width: 150px;
grid-area: 1/1;
/* adjust the 180px to control the placement */
offset: circle(180px) calc(100%*sibling-index()/sibling-count()) 0deg;
}
See the Pen Images around a circle by Temani Afif (@t_afif) on CodePen.
We go fancy by adding a nice entry animation using @starting-style
.container img {
transition: 1s 1s;
@starting-style {
offset: circle(0px) 0% 0deg;
}
}
See the Pen Images around a circle + animations by Temani Afif (@t_afif) on CodePen.
More CSS Tips
- Get the index of an element within its parent A native CSS function to get the index of an element among its siblings within a parent element.
- Invert CSS Shapes using shape() A simple trick to get the cut-out version of any shape created using shape().