我可以为 css 写一个循环吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16987692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:08:43  来源:igfitidea点击:

can I write a loop for css

css

提问by soum

I have a scenario where I am getting ID generated like this

我有一个场景,我会像这样生成 ID

<div class="containerLength">
<div id="new-1"></div>
<div id="new-2"></div>
<div id="new-3"></div>
<div id="new-4"></div>
</div>

and so on

等等

is there a way I could write some css to target them through a loop? maybe something like

有没有办法我可以编写一些 css 来通过循环定位它们?也许像

#new[i; for(i=0; i<="containerLength.length"; i++)]{
float:left;
}

Probably I am day dreaming correct?

可能我是在做白日梦吧?

回答by Prisoner

You can't do loops with pure CSS, however, if you're using something like SASS or LESS then you can do both like:

您不能使用纯 CSS 进行循环,但是,如果您使用的是 SASS 或 LESS 之类的东西,那么您可以同时执行以下操作:

SASS:

萨斯

@for $i from 1 through 4
  .#{$class-slug}-#{$i}
    width: 60px + $i

LESS:

Can you do a javascript for loop inside of LESS css?

你能在 LESS css 里面做一个 javascript for 循环吗?

However, assuming you just want to apply the same style to each nested div, you can just do

但是,假设您只想对每个嵌套应用相同的样式div,您可以这样做

.containerLength > div{
  float: left;
}

or perhaps create a class named .float-leftand apply it to each element you want floated right.

或者创建一个名为的类.float-left并将其应用于您想要正确浮动的每个元素。

回答by karthikr

You can do

你可以做

div.containerLength > div { /* > Matches only first level children of the wrapper div */
    float: left;
}

回答by karthikr

div[id|="new"]{
    float: left;
}

documentation

文件

You may or may not need the quotes, it's weird sometimes.

您可能需要也可能不需要引号,有时这很奇怪。

回答by Alexandru R

Why don't you try this:

你为什么不试试这个:

.containerLength > div {float:left}

回答by DougM

you can't write any logic at all in css. you can, however, managed css with JavaScript, or include multiple id's in one rule, or just use a class.

您根本无法在 css 中编写任何逻辑。但是,您可以使用 JavaScript 管理 css,或者在一个规则中包含多个 id,或者只使用一个类。

You also may be able to use Css attribute selectors, depending on how the ids are arranged and how broad you need your browser support to be.

您也可以使用 Css 属性选择器,具体取决于 id 的排列方式以及您需要浏览器支持的范围。

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors