Simplify your CSS with Sass (create a circle with small circles in css)
I am trying to make animation. With 8 small circle, I make a big circle. This is my css code how I have placed my circles. Is there a way to simplify this css with Sass (mixin, loop or functions)?
span:nth-child(1) {
margin-top: -100px;
}
span:nth-child(2) {
margin-top: -70px;
margin-left: 70px;
}
span:nth-child(3) {
margin-left: 100px;
}
span:nth-child(4) {
margin-top: 70px;
margin-left: 70px;
}
span:nth-child(5) {
margin-top: 100px;
}
span:nth-child(6) {
margin-top: 70px;
margin-left: -70px;
}
span:nth-child(7) {
margin-left: -100px;
}
span:nth-child(8) {
margin-top: -70px;
margin-left: -70px;
}
source to share
You can use a loop @for
:
$steps: -100px, -70px, 0, 70px, 100px, 70px, 0, -70px;
@for $n from 1 through 8 {
span:nth-child(#{$n}) {
margin-top: nth($steps, $n);
margin-left: nth($steps, ($n + 1) % 8 + 1); // This is explained in the comments
}
}
Update: using trigonometry
You can use trigonometry to calculate values top
and left
exactly based on value $n
(you can find trigger functions in a number of Sass extensions like Compass, or Google for more details on your own), which would make for cleaner code.
If you have access to the functions pi
, sin
and cos
(using Compass for example), you can calculate the exact values for the positions around the circle based on $n
:
@for $n from 1 through 8 {
span:nth-child(#{$n}) {
margin-top: 100px * sin($n * pi() / 4);
margin-left: 100px * cos($n * pi() / 4);
}
}
* pi() / 4
converts our values $n
1
.. 2
.. 3
.. to PI/4
.. PI/2
.. 3PI/4
.. which are radian equivalents 45 degrees
.. 90 degrees
.. 135 degrees
.. this is exactly what we need.
Update 2: flexible number of small circles
Made a bit more flexible - no longer limited to 8 small circles:
$number-of-circles: 13;
@for $n from 1 through $number-of-circles {
span:nth-child(#{$n}) {
$angle-in-radians: $n * (pi() * 2 / $number-of-circles);
margin-top: 100px * sin($angle-in-radians);
margin-left: 100px * cos($angle-in-radians);
}
}
pi() * 2
is the radian equivalent of 360 degrees. We'll divide this by the number of circles (which gives the angle, in radians, between each circle) and multiply that by $n
to get the radian angle value for each circle.
Working demo: http://codepen.io/anon/pen/grfFD
source to share