0

This code below for the most works. But when I type inside the lines, and suppose the cursor is in the middle of the word, if I play around and press enter and backspace, two numbers will show up on a line. Is there a CSS-only way of fixing this so only one number per line, and the line numbers still match up?

pre {
    background: #303030;
    color: #f1f1f1;
    padding: 10px 16px;
    border-radius: 2px;
    -moz-box-shadow: inset 0 0 10px #000;
    box-shadow: inset 0 0 10px #000;
}

pre span {
  display: inline-block;
    line-height: 1.5rem;
    counter-increment: line;
}
pre span:before {
      
      content: counter(line);
      display: inline-block;

      padding: 0 .5em;
      margin-right: .5em;
      color: #888;

}
<pre contenteditable="true" spellcheck="false">
<span>lorem ipsum</span>
</pre>
Teg Louis
  • 115
  • 4

1 Answers1

0

UPDATE: Just tested on Firefox, different layout so the snippet below does not number the lines. (FF just puts in <br> rather than any further HTML structure).

Will leave this answer up for a bit in case it helps someone get to a general answer for all common browsers.

ORIGINAL ANSWER: At least on Edge/Chrome the extra lines seem to be encased in div elements.

This snippet numbers the first line, which is just a span, in the same way that you have done but then numbers using the counter called line on the div immediate children of the pre rather than on the encased spans.

pre {
  background: #303030;
  color: #f1f1f1;
  padding: 10px 16px;
  border-radius: 2px;
  -moz-box-shadow: inset 0 0 10px #000;
  box-shadow: inset 0 0 10px #000;
  counter-reset: line 1;
}

pre>span::before {
  content: '1';
  display: inline-block;
  padding: 0 .5em;
  margin-right: .5em;
  color: #888;
}

pre div {
  line-height: 1.5rem;
  counter-increment: line;
}

pre div::before {
  content: counter(line);
  display: inline-block;
  padding: 0 .5em;
  margin-right: .5em;
  color: #888;
}
<pre contenteditable="true" spellcheck="false">
<span>lorem ipsum</span>
</pre>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • It solves the original problem. But if you add another span, it still stays at one. But it helped me with the next step. But it still doesn't work in Firefox. – Teg Louis Apr 14 '22 at 01:51
  • You can set things for further spans at the same level as a div too, but nothing is going to get it working on FF other than some JavaScript coding. – A Haworth Apr 14 '22 at 10:48