Ahmed El Gabri

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_

@mixin auto-numbers($numbered-element, $sep, $counter: item, $nested-parent: false ){
    $sel: ();
    @if $nested-parent {
        $sel: append($sel, unquote($nested-parent));

        #{$nested-parent}{
            list-style: none;
            margin-left: 0;
        }
    }
    $sel: append($sel, unquote('&'), comma);

    #{$sel}{
        counter-reset: #{$counter};
        > #{$numbered-element}{
            &:before{
                counter-increment: #{$counter};
                content: if($nested-parent, counters(#{$counter}, "#{$sep} ") "#{$sep} ", counter(#{$counter}) "#{$sep} ") ;
            }
        }
    }
}

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.

You can tweet this post or reach out directly to me @ahmedelgabri.

© 2024 Ahmed El Gabri