13

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?

soum
  • 1,131
  • 3
  • 20
  • 47

5 Answers5

17

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.

Community
  • 1
  • 1
Prisoner
  • 27,391
  • 11
  • 73
  • 102
4

You can do

div.containerLength > div { /* > Matches only first level children of the wrapper div */
    float: left;
}
karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 1
    You don't really need the initial 'div', '.containerLength > div' is enough. – Marco Luglio Jun 07 '13 at 15:31
  • @facildelembrar I normally like keeping things more explicit. I agree that it is not required. – karthikr Jun 07 '13 at 15:32
  • 2
    With CSS, it's better to be too specific than not specific enough. Only select exactly what you want to change, and nothing more. I can't tell you how many work hours I've spent fixing bad CSS selectors. –  Jun 07 '13 at 15:36
  • 2
    I used to agree with you guys and use a tag selector along with a class selector. What made me change my mind was performance, and to a lesser extent, file size. Check your pages with yslow and pagespeed. – Marco Luglio Jun 11 '13 at 09:28
3
div[id|="new"]{
    float: left;
}

documentation

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

2

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

DougM
  • 2,808
  • 17
  • 14
1

Why don't you try this:

.containerLength > div {float:left}
Alexandru R
  • 8,560
  • 16
  • 64
  • 98