flightdroid.com

a code example repository

Code Blocks with Line Numbers

This is pretty useful for sites like this. It's actually pretty simple. A couple of lines of CSS and wrap the code you want displayed in a code tag.

Reset the line counter every time we use the pre tag.

Increment the line counter every time we use the code tag.

Next use the :before psuedo-element to do the work for displaying the line numbers.

  • display the line number
  • set the width of the line number column
  • show a border between the code and the line numbers
  • use -webkit-user-select: none; so that just the code is selected and not the numbers
pre{
    counter-reset: line;
}

code{
    counter-increment: line;
}

code:before{
    content: counter(line);
    width: 3em;
    display: inline-block;
    border-right: 1px solid #ddd;
    padding: 0 .5em;
    margin-right: .5em;
    color: #888;
    -webkit-user-select: none;
}