使用Sass简化CSS(在css中使用小圆圈制作圆圈)

Sal*_*oui 3 css sass

我正在尝试做一些动画.用8个小圆圈我做了一个大圆圈.这是关于我如何放置圈子的css代码.有一种方法可以用Sass(mixin,循环或函数)简化这个css吗?

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;
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*hai 5

你可以使用一个@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
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:使用三角法

您可能希望使用三角函数来精确计算topleft估计值$n(您可以在许多Sass扩展中找到trig函数,例如Compass,或Google以获取有关自己滚动的详细信息),这样可以使代码更清晰.

如果你有机会获得pi,sincos功能(如使用指南针),你可以计算出基于绕了一圈位置精确值$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);
  }
}
Run Code Online (Sandbox Code Playgroud)

* pi() / 4我们的转换$n价值1.. 2.. 3..到PI/4.. PI/2.. 3PI/4它们的弧度等价物.. 45 degrees.. 90 degrees.. 135 degrees..这正是我们所需要的.

更新2:灵活的小圆圈数量

使其稍微灵活一点 - 不再局限于8个小圆圈:

$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);
  }
}
Run Code Online (Sandbox Code Playgroud)

pi() * 2相当于360度的弧度.我们将其除以圆的数量(以弧度表示每个圆之间的角度),并将其乘以$n得到每个圆的弧度值.

工作演示:http://codepen.io/anon/pen/grfFD