0

Here is my code:

<? for($x = 0; $x < count($groupSmall); $x++){ ?>
    <div class="col-md-3 meeting-item">
        <img src="images/image.jpg" />
    </div>
<? } ?>

I would like to add a new class to every 4th div in this loop. I know it can be done with Modulus but I can't get it to work.

Thanks!!!

4 Answers4

2
<? for($x = 0; $x < count($groupSmall); $x++){ ?>
    <div class="col-md-3 meeting-item <?= $x % 4 === 0 ? 'my-class' : null ?>">
        <img src="images/image.jpg" />
    </div>
<? } ?>

PHP documentation

Oswaldo Acauan
  • 2,730
  • 15
  • 23
2

Why not just use nth-child(4n)? JSFiddle example.

<? for($x = 0; $x < count($groupSmall); $x++){ ?>
    <div class="col-md-3 meeting-item">
        <img src="images/image.jpg" />
    </div>
<? } ?>

...remains unchanged. And in your CSS:

div.meeting-item:nth-child(4n){
    background-color:#EEE;
}
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

I can't comment on Oswaldo's answer because I don't have the reputation yet, but if you just replace the "0" by a 3, as so, you'll get the class added to the 4th 8th etc.

<? for($x = 0; $x < count($groupSmall); $x++){ ?>
    <div class="col-md-3 meeting-item <?= $x % 4 === 3 ? 'my-class' : null ?>">
    <img src="images/image.jpg" />
</div>
<? } ?>
0

You souldn't use PHP for this kind of stuff. That's what CSS is for. Let's say you have a container and the divs inside, the container is divContainer. So, in CSS:

#divContainer div .meeting-item:nth-child(4n+4){
   //apply style.
 }
danielrozo
  • 1,442
  • 1
  • 10
  • 22