htmlcsssyntaxformattingpre

Write webpage text in <code> or <pre> while keeping < and > tags in the text - (ie. "<mycustomtag>")


I have this C++ code (see my jsfiddle):

#include <ossource>

int main()
{
    std::cout << "Hello World! \n";

    return 0;
}

I am trying to include that in a code section on my webpage with the indents etc intact, however when I place it in <pre> tag (or similar) it doesn't like the <ossource> part because it believes the angled brackets < and > are html, not raw text. So it removes them (see jsfiddle above).

Is there an easy way to display this code exactly as it is?

I have tried using <code> and <pre> to no avail.


Solution

  • use HTML entities for < and > characters

    To render language-reserved characters like <, >, or \, it's common to escape the symbol, so that it won't be interpreted as part of language syntax.

    You could use &lt; or &#60; for < sign, and &gt; or &#62; for > sign in HTML.

    See the sample snippet below.

    <pre>
      <code>
        #include &lt;ossource&gt;
    
        int main()
        {
          std::cout << "Hello World! \n";
    
          return 0;
        }
      </code>
    </pre>
    
    <hr />
    
    <pre>
      <code>
        #include &#60;ossource&#62;
    
        int main()
          {
            std::cout << "Hello World! \n";
    
            return 0;
          }
      </code>
    </pre>