I have three CSS rules that define alternating styles, repeating every three items:
.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.
However, once applied to a website that writes multiple div.container
s using a PHP foreach
loop, the styles no longer alternate. Apparently only the nth-child(3n-2)
style is now being applied to all .container
s. The PHP looks like this:
<?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); apparently, every last one of those divs is now the first (and therefore only) child of its parent. 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.
For future help with debugging nth-child issues, this is handy: http://css-tricks.com/examples/nth-child-tester/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.