Home > Software engineering >  What is the correct way to use PRE or CODE tags with a OL list inside
What is the correct way to use PRE or CODE tags with a OL list inside

Time:10-02

The best way is to give an example.

<!DOCTYPE html>
<HTML lang="en">

<HEAD>
  <TITLE>PRE - CODE - OL test</TITLE>
</HEAD>

<BODY>
  <PRE><CODE>
    <OL>
    <LI></LI>
    </OL>
    </CODE></PRE>
  <PRE>
    <OL>
    <LI></LI>
    </OL>
    </PRE>
  <CODE>
    <OL>
    <LI></LI>
    </OL>
    </CODE>
</BODY>

</HTML>

The html validator tool returns:

":8.1-8.4: error: Element “ol” not allowed as child of element “code” in this context.
":12.6-13.4: error: Element “ol” not allowed as child of element “pre” in this context.
":18.1-18.4: error: Element “ol” not allowed as child of element “code” in this context.

Now, the document I'm creating displays exactly the way it should in Firefox and Edge, so I don't see a problem other than the syntax isn't valid HTML. So, how do I achieve the same result with valid HTML?

Edit: For those who want to see what my actual document looks like, here is the link. Be aware, the document is over 100K in size.

CodePudding user response:

The <code> and <pre> elements only permit phrasing content.

The <ul> and <ol> elements are flow content, and if their children include at least one <li> element, palpable content.

Consider escaping some of the html tag characters so that the browser treats each code snippet as plain text and not html.

<pre>
  <code>
      &lt;ol&gt;
        &lt;li&gt;&lt;/li&gt;
      &lt;/ol&gt;
  </code>
</pre>
<pre>
    &lt;ol&gt;
      &lt;li&gt;&lt;/li&gt;
    &lt;/ol&gt;
</pre>
<code>
    &lt;ol&gt;
      &lt;li&gt;&lt;/li&gt;
    &lt;/ol&gt;
</code>

Edit.

If all you need is line numbers, perhaps this approach without ordered lists would pass validation.

code {
  white-space: pre-wrap;
  background: lightseagreen;
  padding: 1em;
  margin: 1em;
  display: block;
}

code:before {
  counter-reset: listing;
}

code>span {
  counter-increment: listing;
}

code span::before {
  content: counter(listing) ". ";
  color: yellow;
  font-weight: bold;
}
<code>
<span>// WL_MAIN.C</span>
<span></span>
<span>#include "WL_DEF.H"</span>
<span>#pragma hdrstop</span>
</code>

  •  Tags:  
  • html
  • Related