【问题标题】:css increment nth-child attribute valuescss 增加第 n 个子属性值
【发布时间】:2015-01-14 09:40:42
【问题描述】:

有没有办法使用nth-child(n)中的n来增加属性值以输出结果:

div:nth-child(1){
    top: -5px;
}
div:nth-child(2){
    top: -10px;
}
div:nth-child(3){
    top: -15px;
}
div:nth-child(4){
    top: -20px;
}
div:nth-child(5){
    top: -25px;
}

【问题讨论】:

  • 如果你使用preprocessor,例如sass
  • ...或者用jquery添加: $('div').each(function(i=1){$(this).css("top", -5*i); i++;});

标签: css attributes css-selectors increment


【解决方案1】:

如果你使用preprocessor 就像sass 一样,你可以。

一个例子:

div {
  $var: 5;

  @for $i from 1 through 5 {
    &:nth-child(#{$i}) {
      top: -#{$var}px;
      $var: $var + 5;
    }
  }
}

一个演示:http://sassmeister.com/gist/7d7a8ed86e857be02d1a

实现此目的的另一种方法:

div {

  $list: 1 2 3 4 5;

  @each $i in $list {
    &:nth-child(#{$i}) {
      top: -5px * $i;
    }
  }
}

一个演示:https://www.sassmeister.com/gist/fb5ee7aa774aafb896cd71a828882b99

【讨论】:

  • 如果数字是动态的,你能发布一个与声明等效的 foreach 吗?
  • 但这只有在你知道你有 5 个元素的情况下才有效。如果元素是动态添加的呢?
  • SCSS 总是在 CSS 中翻译,所以你不能有一个动态变量。我想您正在寻找一种仅使用 css 的方法来实现此目标,例如 nth-child(n+1) { top: -5px * n},但不幸的是这行不通。
猜你喜欢
  • 2018-03-09
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多