Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

How do I apply a specific css class to every third in a list WordPress

  • SOLVED

I'm trying to find a way to apply a specific css class to every third list item in a list of posts. For example...

<li>post title 1</li>
<li>post title 2</li>
<li class="XYZ">post title 3</li>
<li>post title 4</li>
<li>post title 5</li>
<li class="XYZ">post title 6</li>


ideally I'd like the code to be a function in my functions.php file AND the ability to have multiple instances for different lists.

What I'm trying to do is to get the page list wrap as per this template...
http://www.getfreewebdesigns.com/preview/?template=778

So if you know a better way then by all means let me know that too.

Thanks

$10 up fro grabs

Answers (2)

2010-04-11

Jarret Minkler answers:

So usually you would have a loop in php displaying your list

<ul>
<?php $counter = 0; foreach ($listitems as $item) : ?>
<?php if ($counter % 3 == 0) : ?>
<li class="everythird"><?php echo $item; ?></li>
<?php else : ?>
<li><?php echo $item; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>

in JS it's much the same thing you want to use the modulo (remainder after division) operator to compare the counter in the loop the operator is %

so for example ... 27 % 3 = 0 so this is one of every third.

if js pick your favorite framework, you might need to give each li an id as not to keep a global counter?

pseduocode:

$counter = 0;
$('#myul li').each(function(ele){
if($counter++ % 3 == 0){ ele.addClassName('mythird') }
});

2010-04-10

Brian Richards answers:

The fastest way I can think of to add a class for every third (or Nth) element would be to use jquery and it's wonderfully advanced selector system. CSS3 can also do this, but you lose cross-browser compatibility.

Granted, you could write a simple function that loops through and does this in PHP, but if you're already using jquery for anythnig else, why not just use that? (1 line vs 12).

Of course, you shouldn't even need to target every third article specifically. If you've done your markup correctly, just giving the articles a proper width and margin will force them to wrap within their containing element when you set them to float:left.


pjeaje comments:

I'd love both versions (js Vs php) so i could use each version depending on my needs.


pjeaje comments:

If you wanna check out the template and help out with the markup to make it wrap then that would be even better :)


pjeaje comments:

solved... the markup was fine in the first place... just too much padding


Brian Richards comments:

Yeah, that's what usually gets me. Some combination of padding, margin and border. I try and give myself a couple pixels of wiggle room to accomodate for rendering in different browsers.