Automatic sub menu counters with CSS
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
README.md
index.html

README.md

#Automatic sub menu counters with CSS

I really think we don't use the CSS counter functions enough.
They don't even use it in the CSS spec to add automatic numbering to the list of links!

We can even use this CSS property to automatically count our sub menu items. This is really helpful because the count will automatically be updated in case we add more items dynamically (Ajax calls).

The markup is basic, no need to use spans or any other elements for the numbers:

<ul>
    <li>
		<a href="#">link</a>
		<ul>
			<li>Item</li>
			<li>Item</li>
			<li>Item</li>
			...
		</ul>
	</li>
	...
</ul>

And then in the CSS you just have to:

/* reset the counter for every sub menu */
ul > li > ul { counter-reset: items; }

/* increment the counter */
ul > li > ul > li { counter-increment: items; }

/* Display the total number of items in the "after" pseudo-element" */
ul > li > ul:after { content: counter(items); }

This technique is compatible with all modern browsers and IE8+.

See how it looks here.