Html Code Block with Examples

0
155
Html Code Block with Examples

Html Code Block with Examples

To create a code block in HTML, you can use the <pre> element and the <code> element. The <pre> element indicates that the text inside is preformatted and should be displayed exactly as written. The <code> element indicates that the text inside is a block of code.

Here is an example of how you can use these elements to create a code block:

<pre>
<code>
// This is a code block
function sayHello() {
console.log("Hello, World!");
}
</code>
</pre>

You can also use the <pre> element on its own to create a code block, like this:

<pre>
// This is a code block
function sayHello() {
console.log("Hello, World!");
}
</pre>

Note that the <pre> element preserves whitespace, so any indents or line breaks in your code will be preserved when it is displayed in the browser.

Here are a few more examples of how you can use the <pre> and <code> elements to create code blocks in HTML:

Example 1: Use the <pre> and <code> elements to display a block of HTML code:

<pre>
<code>
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;My Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Welcome to my page!&lt;/h1&gt;
&lt;p&gt;This is some content.&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>
</pre>

Example 2: Use the <pre> element on its own to display a block of JavaScript code:

<pre>
function sayHello() {
console.log("Hello, World!");
}
</pre>

Example 3: Use the <code> element within a paragraph to display a block of code inline:

<p>To run the script, use the following command: <code>./myscript.sh</code></p>