Preformatted Text with Line Numbers

I was trying to figure out how to add line numbers to preformatted text for another entry. I couldn't find a satisfactory solution, so I ended up creating my own. I'm happy with it so far, so I'm posting about that instead.

Here's the markup. Basically, I used an ordered list (ol) to get the line numbers, since it's built-in and will save me from having to count. Pretty self-explanatory.

  1. <div class="numbered">
  2. <ol>
  3. <li>This is line one</li>
  4. <li> This is line two</li>
  5. <li> This is line three</li>
  6. <li> This is line four</li>
  7. <li class="last">This is line five</li>
  8. </ol>
  9. </div>

CSS is below. The only important piece of css is the white-space: pre;. This tells the list items (li) to act like pre tags and pay attention to spaces. This of course allows you to indent your lines.

  1. div.numbered {
  2. background-color: #EDC850;
  3. border: 2px solid #900701;
  4. color: #f7f2de;
  5. font-family: "courier new", monospace;
  6. margin: 2em;
  7. font-size: .8em;
  8. overflow: auto;
  9. }
  10.  
  11. div.numbered ol li {
  12. background-color: #fdf3f3;
  13. border: 1px solid #EDC850;
  14. border-style: none none solid solid;
  15. color: black;
  16. padding: 3px 10px;
  17. white-space: pre;
  18. }
  19.  
  20. /* Prevent a double border */
  21. div.numbered ol li.last {
  22. border-bottom-style: none;
  23. }

Works in all sensible browsers and IE6+. However, IE needed me to remove whitespace between my list items because of the whitespace bug. 456 Berea St. presents another option.

I'll probably see if I can whip up some JavaScript to handle this with less markup later.

TIP: An easy way to mark up lists quick, which works in most advanced text editors, is to hold alt and select text in a column. This allows you to type into many rows at once (useful for repetitive opening and closing tags)

That's it, enjoy!

  • Posted by Jason Peddle on April 11th, 2008 @ 12:46 p.m.

    Thanks for the heads-up, although I think I'll keep working on it, because overflow auto takes the underlying div background-color on the overflow, and loses the lines.

  • Posted by Adrian Rosebrock on April 11th, 2008 @ 12:10 p.m.

    If the line of code is longer than the with of li or ol, then the code extends past the desired width. You need to include overflow: auto; in your css for the ol tag.