Improves logic to determine when to add the 'first' and 'last' CSS classes.