简体   繁体   English

PHP构造站点中的CSS:nth-​​child()选择器

[英]CSS :nth-child() selector in a PHP constructed site

I have three CSS rules that define alternating styles, repeating every three items: 我有三个CSS规则定义交替的样式,每三个项目重复一次:

.container:nth-child(3n):after {
    /* Styleset 1 */
}

.container:nth-child(3n-1):after {
    /* Styleset 2 */
}

.container:nth-child(3n-2):after {
    /* Styleset 3 */
}

These work flawlessly in simple static HTML pages. 它们可以在简单的静态HTML页面中完美地工作。

However, once applied to a website that writes multiple div.container s using a PHP foreach loop, the styles no longer alternate. 但是,一旦应用到使用PHP foreach循环编写多个div.container的网站,样式便不再交替。 Apparently only the nth-child(3n-2) style is now being applied to all .container s. 显然,现在仅将nth-child(3n-2)样式应用于所有 .container The PHP looks like this: PHP看起来像这样:

<?php foreach ($articles as $article) { ?>
    <div class="container">
        <!-- Content creation -->
    </div>
<?php } ?>

How does this happen? 这是怎么发生的?

If n is the first child, (3n-2) would compute to (3-2 = 1); 如果n是第一个孩子,则(3n-2)将计算为(3-2 = 1); apparently, every last one of those divs is now the first (and therefore only) child of its parent. 显然,这些div中的每个最后一个现在都是其父级的第一个(因此也是唯一的)子级。 I can't tell you exactly what to fix without seeing the rest of your code (is this loop inside of another loop which is creating a parent for each one?), but you probably have to move that loop up a level or otherwise ensure that all of your .containers are being created as siblings, and not as lonely, single children. 在看不到代码其余部分的情况下,我无法确切告诉您要解决的问题(此循环是否在为每个循环创建父级的另一个循环内?),但是您可能必须将该循环上移,否则必须确保您所有的.container都被创建为兄弟姐妹,而不是一个孤独的独生子女。

For future help with debugging nth-child issues, this is handy: http://css-tricks.com/examples/nth-child-tester/ 对于以后调试nth-child问题的帮助,这很方便: http : //css-tricks.com/examples/nth-child-tester/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM