Dibash Thapa

TIL: Line number using css

I was trying to make a vim like editor in web with html and javascript. And today I learned that, you could usually display lines using just css in your custom web editor.

I used to think, that you would have to use js, then use complex state in your editor, and store line numbers differently, handling all the edge cases, and dynamically pushing the css styles during runtime. I was also confused about taking care of full width input in your screen while making an editor.

TIP 💡

Taking care of full screen editor

  <div id="content" contenteditable="true"></div>

I knew about contenteditable already, but underestimated its application in making a text editor.

Rendering Lines using CSS

div:focus {
  outline: none;
  counter-reset: line;
  overflow-y: auto;
  padding-left: 48px;
  font-family: 'Courier New', Courier, monospace;
}

#content {
  padding-top: 10px;
  font-size: 24px;
  background-color: #fff;
  height: 100vh;
}

#content div {
  position: relative;
  display: block;
  white-space: pre-wrap;
}

#content div::before {
  content: counter(line);
  counter-increment: line;
  position: absolute;
  right: calc(100% + 16px);
  opacity: 0.5;
}

When you use div with contenteditable and type in multiple new lines, then the browser appends multiple div elements. So every div element is a new line.

And css has this great property to take care of lines

content: counter(line);
counter-increment: line;

----
counter-reset: line;

So, you can adjust padding, margin and colors based on your preferences