Textpattern tips, tutorials and code snippets

Apply a style to every third article in a list

As a follow up to the previous TXP Tip on Article lists with alternate backgrounds, here is a method of styling every third article in a list differently from the others.

  1. Download, install and activate the smd_if plugin – minimum version 0.8 required
  2. Download, install and activate the adi_calc plugin

Your code

<txp:variable name="count" value="0" />
<txp:article wraptag="ul" sort="Posted asc">
	<txp:adi_calc name="count" add="1" />
	<txp:smd_if field="txpvar:count" operator="divisible" value="3">
		<txp:variable name="class" value="red" />
	<txp:else />
		<txp:variable name="class" value="normal" />
	</txp:smd_if>
	<li class="<txp:variable name="class"/>"><txp:title /></li>
</txp:article>

The article list is wrapped in a <ul> by the <txp:article/> tag and the individual articles are wrapped in a <li> within the form.

I set a counter to zero (a TXP variable called count) and increment it by one for each article in the list.

The counter is tested by smd_if to see if it is divisible by 3, and if it is then set a different class (i.e. red).

The normal or red class is applied to the <li>.

The result is that the 3rd, 6th, 9th … article title appears with a different (i.e. red) style.

6 Comments Comment feed

The venerable zem_nth still works, and gives a single-plugin solution to this problem. This would work:

<txp:article wraptag="ul" sort="Posted asc">
	<txp:zem_nth step="3" of="3">
		<li class="red"><txp:title /></li>
	</txp:zem_nth>
	<txp:zem_nth step="1-2" of="3">
		<li><txp:title /></li>
	</txp:zem_nth>
</txp:article>

Same thing more concisely:

<txp:article wraptag="ul" sort="Posted asc">
	<li<txp:zem_nth step="3" of="3"> class="red"></txp:zem_nth>><txp:title /></li>
</txp:article>

The problem with zem_nth is that is does not scale well. If you try to use two different calls to zem_nth on the same page you will run into problems. It’d be great if you could add an “id” so the counter would stay within a certain scope.

In almost all situations I end up using txp:variable and a ton of extra code because of zem_nth’s issues.

Excellent, just what I needed.

You also need adi_calc plugin though, which the article doesn’t mention.

Thanks a lot Richard for spotting the error. I have corrected the article to add adi_calc.

A great tip! I use zem_nth for a grid design though. Jsoo is right, it still works perfectly for TXP 4.4.1!

  • etc
  • 24 July 2012

:nth-of-type(3n) css selector works perfectly too nowadays.

Add a comment

Use Textile help to style your comments