如何使用PHP和CSS nth-child生成ABBAABBA ...序列 [英] How to generate ABBAABBA... sequence with PHP and CSS nth-child

查看:33
本文介绍了如何使用PHP和CSS nth-child生成ABBAABBA ...序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列布局,其中元素的配置如下:

I have a two column layout with this disposition of elements:

A B
B A
A B
B A

A B
B A
A B
B A

A B 元素的内容来自不同的来源和样式.因此,我试图找到一个表达式来在PHP和CSS nth-child中生成此 A B B A A B B A…序列.

A and B elements have content from different origins and also different styles. So, I'm trying to find an expression to generate this A B B A A B B A … sequence both in PHP and CSS nth-child.

这就是我要生成的布局:

This is what I'm doing to generate the layout:

/* $post_ids is an Array of ID's */

$count = count( $post_ids );

for ( $i = 0; $i < $count; $i++ ) {
    $classes = ['teaser', 'lg-6', 'md-6', 'sm-12'];
    if ( ( 2 * $i ) % 2 == 0 ) { // This is wrong. Always true!
        $classes[] = 'a-element';
    } else {
        $classes[] = 'b-element';
    }
    insert_post( $post_ids[ $i ], $classes ); // This is a custom function
}

这是我的CSS:

.teaser:nth-child(2n) { // Also wrong
    /* Styles for A items */
}

我知道一旦获得正确的PHP序列,我就可以将CSS替换为:

I know once I got the correct PHP sequence I could replace my CSS with:

.a-element {…}
.b-element {…}

但是我想知道是否也可以使用 nth-child ...

But I'd like to know if this could be also done with nth-child...

我想这并不难,但是我对此感到有些困惑...任何提示或帮助都将不胜感激!

I guess it can't be that hard, but I'm kinda stuck with this... Any hint or help will be much appreciated!

编辑:@axiac的回答和一些

After @axiac's answer and some research, I've learned that nth-child only allows:

  • 一个数字-任何正整数(1、2、3、20等)
  • 关键字-偶数或奇数
  • 表达式-形式为an + b(a,b为整数)

所以,我想我想用CSS的 nth-child 做不到的事情.谢谢你们!

So, I guess what I want can't be done with CSS's nth-child. Thank you guys!

推荐答案

您需要的PHP代码是:

The PHP code you need is:

if ((int)(($i + 1) / 2) % 2 == 0 ) {
    $classes[] = 'a-element';
} else {
    $classes[] = 'b-element';
}

更新

应OP的要求,这就是我产生上面代码的方式.理想的结果是:

At OP's request, this is how I produced the code above. The desired outcome is:

A B B A A B B A ..

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆