有没有一种方法可以使用"n":nth-​​child(n)中的值? [英] Is there a way to use the "n" value in :nth-child(n)?

查看:55
本文介绍了有没有一种方法可以使用"n":nth-​​child(n)中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个折叠效果.

I want to create a fold effect.

小提琴

有4张蓝卡,所以我创建了4个类来设置位置.如果要多于4张卡,我想使其变得更智能.在CSS中,我尝试了这一点.

There are 4 blue cards, so I created 4 classes to set the location. I want to make it smarter, in case there would be more than 4 cards. In CSS, I tried this.

.card:nth-child(n){
    position: absolute;
    left: calc(n*10)px;
    top: calc(n*10)px;
}

但是,它不起作用.有办法吗?

However, it does not work. Is there a way to do that?

推荐答案

CSS不支持变量.您可以使用Less/SASS循环并为n定义它,直到一个值,但这样会多次输出几乎相同的CSS.这是 Codepen 示例.

CSS doesn't have support for variables. You could use Less/SASS loops and define it for n up to some value, but that would output almost the same CSS multiple times. Here is Codepen example.

SCSS代码最多可支持10张卡:

SCSS code to support up to 10 cards:

$n: 10;

@for $i from 1 through $n {
  .card:nth-child(#{$i}) {
    position: absolute;
    left: 10px * $i;
    top: 10px * $i;
  }
}

但是您确定您的方法正确吗?也许您想退后一步,寻找另一种方法.由于这仍然无法动态扩展,因此您必须预测 n 或将其限制为某个值.如果您选择大的 n ,则会导致CSS文件大,这意味着加载时间更长.

But are you sure your approach is correct? Maybe you want to take a step back and look for a different approach. Because this still doesn't scale dynamically, you'll have to predict or limit n to some value. If you were to pick large n, it would result in a big CSS file, which equals longer load times.

这篇关于有没有一种方法可以使用"n":nth-​​child(n)中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆