1.

How do you display lines of code on a web-page using HTML?

Answer»

We can display a code block in our HTML using the combination of <pre> and <code> tag. The <code> tag only represents a single line and if we wrap our complete code in the <code> tag, it will be displayed in a line.

So, we use it in combination with <pre> tag. We basically wrap everything inside a <pre> tag. The <pre> tag stand for reformatted test. So, anything we give inside it including line breaks will be shown.

We will add some code to display in our canvas example in Question 18.

<!DOCTYPE html> <html> <head>    <title>Code Demo</title>    <style>        .grid__iframe {            display: grid;            place-content: CENTER;        }        h1,H4{            text-align: center;        }    </style>    <script TYPE="text/javascript">        window.onload = function () {            var canvas = document.getElementById('canvas');            var ctx = canvas.getContext('2d');            //square 1            ctx.fillStyle = 'green';            ctx.fillRect(100, 10, 100, 100);            //square 2            ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';            ctx.fillRect(150, 50, 100, 100);        }    </script> </head> <body>    <div class="grid__iframe">        <h1>HTML Canvas</h1>        <canvas id="canvas" width="300" height="300">            This canvas shows two operlapping squares.        </canvas>        <h4>Code for the canvas</h4>         <pre>             <code>                 window.onload = function () {                     var canvas = document.getElementById('canvas');                     var ctx = canvas.getContext('2d');                     //square 1                     ctx.fillStyle = 'green';                     ctx.fillRect(100, 10, 100, 100);                     //square 2                     ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';                     ctx.fillRect(150, 50, 100, 100);                 }             </code>         </pre>    </div> </body> </html>



Discussion

No Comment Found