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.
- <div class="numbered">
- <ol>
- <li>This is line one</li>
- <li> This is line two</li>
- <li> This is line three</li>
- <li> This is line four</li>
- <li class="last">This is line five</li>
- </ol>
- </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.
- div.numbered {
- background-color: #EDC850;
- border: 2px solid #900701;
- color: #f7f2de;
- font-family: "courier new", monospace;
- margin: 2em;
- font-size: .8em;
- overflow: auto;
- }
- div.numbered ol li {
- background-color: #fdf3f3;
- border: 1px solid #EDC850;
- border-style: none none solid solid;
- color: black;
- padding: 3px 10px;
- white-space: pre;
- }
- /* Prevent a double border */
- div.numbered ol li.last {
- border-bottom-style: none;
- }
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!
- css
- April 11th, 2008 @ 8:30 a.m.
- Add Comment

Smashing Magazine
Lifehacker
Thoughts From Eric


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