0

I want to display source code with line numbers in a web page. (Unfortunately I cannot use existing highlighting components like google-code-prettify because I must use my own syntax parser.)

To prevent the line numbers from copy&paste with the source code I use a table with one row and two cells: In the first cell there are the line numbers, in the second cell is the source code:

<html><body>
<table>
  <tr>
    <td>1<br/>2<br/>3</td>
    <td>
      <pre>int main() {
    println("I am a very looooooooooooooooog source code line.")
  }</pre>
    </td>
  </tr>
</table>
</body></html>

This works, but I have problems with long source code lines: The table gets very wide. If I break long lines the line numbers on the left side are not correct anymore.

The best solution would be a table were the user can scroll wide lines, just like this example from GitHub on line 88. I have tried with various CSS parameters like overlay, width, white-space but I didn't get the result from GitHub.

How can I scroll vertical long lines in a table without scrollbars?

(Or is there a better solution to display code with line numers without tables? I have seen solutions that uses an ordered list or an textarea, but they also have problems.)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sonson123
  • 10,879
  • 12
  • 54
  • 72
  • So what are the problems that lists and textareas have that prevents your using them? And you'll notice that the example you link to uses `div` elements for the lines? – David Thomas Feb 14 '13 at 14:32

2 Answers2

1

You'd need to give the table the CSS table-layout:fixed; for those other attributes to come into effect.

I'm not sure how you'd make it scroll without displaying scrollbars, however. But would your line numbers not be in their own table cells anyhow (so even if the code row spanned multiple lines the numbers would still match up)?

Edit: JSFiddle. You could attempt to hide the scrollbar, somehow.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Thanks. With `table-layout:fixed` and `overflow:scroll` I get the wished result but with a vertical scrollbar. All line numbers are together in *one* table cell (in the GitHub example), so the code should not span multiple lines. I will try to remove the scroll bars or use a one-line-is-one-table-row solution. – Sonson123 Feb 14 '13 at 14:52
  • 1
    You'll need to look into a way of hiding the scrollbar. http://stackoverflow.com/questions/3296644/how-to-hide-scrollbar has an answer with a way of doing so in webkit browsers. – James Donnelly Feb 14 '13 at 14:55
1

Try setting up your code table cells thus:

<td>
  <div class="scrollable">
    <pre>int main() {
         println("I am a very looooooooooooooooog source code line.")
         }</pre>
  </div>
</td>

and have a class:

.scrollable {
  overflow: scroll;
}

See How to create a table cell that scrolls when overflowing

Community
  • 1
  • 1
Raad
  • 4,540
  • 2
  • 24
  • 41