问题
I would like to use modulus to apply a CSS class to a grid of images in two different situations:
Situation 1
I would like to apply a CSS class to all middle images indicated by the *. I cannot simply use nth-child as I do not know if there will always be 9 images in the grid. Sometimes there could be 5, sometimes 7, sometimes 8, etc...it's variable.
[Img 1] [Img 2*] [Img 3]
[Img 4] [Img 5*] [Img 6]
[Img 7] [Img 8*] [Img 9]
Situation 2
I would like to apply a CSS class again to the images in the grid indicated by the *. I also can't use nth-child for the same reason as above. I will add CSS properties to the class given in this situation through a media query as the site has less width, hence the two columns of images.
[Img 1] [Img 2*]
[Img 3] [Img 4*]
Code I have so far
if ($counter % 3 == 1) {
$situation1 = TRUE;
}
if ($counter % 3 == 0) {
$situation2 = TRUE;
}
$counter++;
<div <?php if($situation1) { post_class('situation1'); } if($situation2) { post_class('situation2'); }><img src="" /></div>
回答1:
The modulus is the remainder of the first operand divided by the second operand, so in your case you would need:
if ($counter % 3 === 2) {
$situation1 = TRUE;
}
if ($counter % 2 === 0) {
$situation2 = TRUE;
}
And you could rewrite that as:
$situation1 = ($counter % 3 === 2);
$situation2 = ($counter % 2 === 0);
However, you can do the same in css using the nth-child
selector (IE9+):
Situation 1:
:nth-child(3n+2)
Situation 2:
:nth-child(2n+2)
来源:https://stackoverflow.com/questions/15650337/how-to-use-modulus-with-php-to-add-a-css-class-to-a-grid-of-images-depending-on