Search code examples
bolt-cms

Odd/even records have unique CSS class


Using Bolt, I'd like to grab my 4 latest entries. Easy enough. However, I need the 1st and 3rd entries to have a specific CSS class around them while the 2nd and 4th entries would have their own class.

Ultimately the HTML should look something like:

    <div class="quarter alt">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>
    <div class="quarter">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>
    <div class="quarter alt">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>
    <div class="quarter">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>

I've played around with the snippets and documentation and am at the point where I found loop.first but of course that only works on the first entry:

{% setcontent records = "entries/latest/4" %}
{% for record in records %}

{% if loop.first %}
    <div class="quarter alt">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>
{% else %}
    <div class="quarter">
        <h3><a href="{{ record.link }}">{{ record.title }}</a></h3>
        <p>{{ record.teaser }}</p>
        <p><a href="{{ record.link }}">Read more</a>.</p>  
    </div>
{% endif %}
{% endfor %}

Any idea how I could edit my template to accomplish what I'm after? Thanks so much.


Solution

  • You can use the css :nth-child selector

    Example:

    .quarter:nth-child(odd) {
        /* CSS for row 1 & 3 */
    }
    
    .quarter:nth-child(even) {
        /* CSS for row 2 & 4 */
    }
    

    (@ruffp, thanks for the feedback)