How to display html code in a html page in a formatted manner

24,684

Solution 1

The most vanilla way to do this and have HTML show up as actual content on your webpage is by wrapping you HTML markup you want to display inside of ' <pre> ' tags.

Then you would need to use HTML entities to show the special characters you need, an open bracket is

&lt; 

and a closing bracket is

&gt;

You can also use a plug-in to help aid in making your code look nice, like for syntax highlighting and more. A pretty nice javascript plug-in can be found here http://prismjs.com/

Solution 2

Use appropriate HTML markup. Don't use <xmp>, which isn't in HTML.

  • Use <pre> to indicate that white space is significant
  • Use entities for characters with special meaning in HTML (e.g. &lt;)
  • Use <code> to mark up code (e.g. <code class="html tag start-tag">&lt;title&gt;</code>).

Apply CSS for the colours you want. The <code> elements give you something to target.

Share:
24,684
Code Hungry
Author by

Code Hungry

Updated on September 11, 2020

Comments

  • Code Hungry
    Code Hungry almost 4 years

    My website is a simple educational one. I want to display HTML code in my web page in a formatted way like they look in a editor. I mean to say the HTML tags should appear in a different color from remaining text etc. This is a code snippet from another website. I want the output of my web page like this:

    enter image description here


    This is my code :-

    <html>
    
    <head>
        <title>HTML Tutorial</title>
    </head>
    
    <body>
        <div class="code">
            <xmp>
                <!DOCTYPE html>
                <html>
    
                <head>
                    <title>HTML Tutorial</title>
                </head>
    
                <body>
                    This is a simple HTML page
                </body>
    
                </html>
            </xmp>
        </div>
    </body>
    
    </html>

    How can I achieve desired behavior in my web page. I thank you all for your efforts.

  • Code Hungry
    Code Hungry about 8 years
    How to add this plug-in to my web page ?
  • Russell Jonakin
    Russell Jonakin about 8 years
    @CodeHungry You can go to the Prism JS website and they have a download page to download any of the Prism JS themes you would like. Then you just need to add the Prism JS css and javascript files to your website. At the bottom of the home page of the Prism JS site there are tutorial links on how exactly to code and use Prism JS.