How to use modulus with PHP to add a CSS class to a grid of images depending on two different patterns?

荒凉一梦 提交于 2020-01-03 05:34:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!