[Fixed]-Li a:nth-child with variable from Django doesn't work as expected

1👍

There are a couple of issues here: nth-child looks for the n-th child element in a group. Your code as it is currently would style the nth a element inside a li tag – but there’s only ever one a in each li. You need to target the li:

li:nth-child({{ active }}) a { text-decoration: underline; }

You also need to make sure that the li items have nothing else alongside them (including style tags), as this will mess up the counter. The template code you’ve posted above is incomplete (we can’t see the outer ul/ol) but if there are other elements inside it then that is a problem.

That said, I don’t think that this is the best approach – dynamic inline styling is not a robust, maintainable solution. A much more common pattern is to add an active class to the active list item, and then have styling for this in your core (static) CSS. See this question for some ideas on how to implement that.

Leave a comment