Sass mixin for auto-numbering with CSS

While I was working on a project at work I needed to have ” table of contents” type of numbering in an <ol> but I wanted the numbers to be nested too like 1. , 1.1, 1.2, etc… which is not possible in HTML. And I remembered that I have faced this problem before & I solved it using CSS Counters and since I use Sass now to write CSS. I thought about creating a @mixin for this. So here you go: Thanks for cimmanon on Stackoverflow for helping me with this

1@mixin auto-numbers($numbered-element, $sep, $counter: item, $nested-parent: false ){
2 $sel: ();
3 @if $nested-parent {
4 $sel: append($sel, unquote($nested-parent));
6 #{$nested-parent}{
7 list-style: none;
8 margin-left: 0;
9 }
10 }
11 $sel: append($sel, unquote('&'), comma);
13 #{$sel}{
14 counter-reset: #{$counter};
15 > #{$numbered-element}{
16 &:before{
17 counter-increment: #{$counter};
18 content: if($nested-parent, counters(#{$counter}, "#{$sep} ") "#{$sep} ", counter(#{$counter}) "#{$sep} ") ;
19 }
20 }
21 }

The @mixin takes four arguments & must be called on the parent element:

$numbered-element The element that you wanted to counted, in my case it was an <li> it can be anything.

$sep s the seprator sign you want to use Must be a string

$counter ounter name, if you are using the @mixin more than once you must change the name for each one so it won’t reset the counter before it.

$nested-parent assing the name of the parent element if you wanted to work in a nested way like a <ol> or <ul> inside another <ol> or <ul>

here is a demo of the mixin in action

See the Pen SASS MIXIN FOR AUTO-NUMBERING WITH CSS by Ahmed El Gabri (@ahmedelgabri) on CodePen.

Useful links about CSS counters