can I write a loop for css

2020-07-10 06:15发布

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

<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

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

Probably I am day dreaming correct?

标签: css
5条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-10 06:40
div[id|="new"]{
    float: left;
}

documentation

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

查看更多
仙女界的扛把子
3楼-- · 2020-07-10 06:42

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

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?

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

.containerLength > div{
  float: left;
}

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

查看更多
在下西门庆
4楼-- · 2020-07-10 06:46

Why don't you try this:

.containerLength > div {float:left}
查看更多
疯言疯语
5楼-- · 2020-07-10 06:57

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.

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.

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

查看更多
等我变得足够好
6楼-- · 2020-07-10 07:04

You can do

div.containerLength > div { /* > Matches only first level children of the wrapper div */
    float: left;
}
查看更多
登录 后发表回答