3

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.

EternalHour
  • 8,308
  • 6
  • 38
  • 57
Code Hungry
  • 49
  • 1
  • 1
  • 6
  • why don't you just take screenshots from the editor and embed them into your code? – Rachel Gallen Jun 13 '16 at 11:56
  • 2
    @RachelGallen — Because pictures of code are awful. They suffer from compression artifacts. Can't be scaled cleanly. Use massively more bandwidth. Are invisible to screen readers. Can't be copy/pasted. – Quentin Jun 13 '16 at 11:57

3 Answers3

7

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/

Russell Jonakin
  • 1,716
  • 17
  • 18
  • How to add this plug-in to my web page ? – Code Hungry Jun 14 '16 at 07:50
  • @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. – Russell Jonakin Jun 14 '16 at 23:02
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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

If you're using Prism as suggested by @JustSomeDude, you might want to use the Unescaped Markup plug-in so that you do not need to use the special characters like &lt; to display your HTML tags.

Margotte
  • 101
  • 1
  • 5