Home > Software design >  How can I generate line number from css or javascript based on height of container
How can I generate line number from css or javascript based on height of container

Time:01-24

I have a situation where I have to make something that looks like a code editor and to acheive this I have to use HTML, CSS and Js without any libraries.

I have achieved pretty much everything except the line numbers and I am not sure how to do it.

So far I have achieved this: enter image description here

and this is what actually is my target: enter image description here

supposing that I have this html structure:

<html>
    <head>
    </head>
    
    <body>
        <div ></div>
        <div ></div>
    </body>
</html>

enter image description here

how do I populate lines based on the height of content in code using CSS or JavaScript?

CodePudding user response:

Here's something: (written fast, feel free to adjust CSS etc)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <style>
    #code {
        line-height: 15px;
    }
    .holder {
        display: flex
    }
    
    </style>
</head>
<body>

        <div >
            <div>
                <pre id="lines">
            </pre>
            </div>
            <div>
                <pre id="code">
                .aaa {
                   bbb
                }
                .ccc {
                   ddd
                }
                </pre>
            </div>
        </div>

</body>
    <script>
    const codeHeight = document.getElementById('code').offsetHeight;    
    const lines = Math.ceil(codeHeight / 15);
    let html = '';
    for (i = 1; i < lines; i  ) {
        html  = i   '<br>'
    }
    document.getElementById('lines').innerHTML = html;  
    </script>
</html>

Here's the JS fiddle: https://jsfiddle.net/4aowc26f/

Number 15 in calculation is due to 15px line height. Feel free to introduce variable for this one.

CodePudding user response:

you should make every line as a div <div><span>{line}</span> <span>some code</span> </div>

  •  Tags:  
  • Related