Nuri Tasdemir
Nuri Tasdemir

Reputation: 9842

Is it OK to use <div> inside <code>?

Is it OK to use "div" tag inside "code" tag? I am using NetBeans 8.0.1 for writing some html pages. And at some point I had to use "div" inside "code". You can see a part of my code in http://jsfiddle.net/125ypcum/

NetBeans gives me the following error

Element "div" not allowed as child of element "code" in this context.

The result is what I want however the error troubles me. Is it a problem in anyway? Is there a way to get the same result without an error?

The code from jsfiddle:

<div class="codeDiv">
<pre>
<code class="black">stat<sub>0</sub>;
<div class="back-red codeBoxMargin">if (expr<sub>1</sub>)
<div class="back-green codeBoxMargin">  if (expr<sub>2</sub>)
    {
        stat<sub>1</sub>;
        stat<sub>2</sub>;
    }
    else
<div class="back-blue codeBoxMargin">       if (expr<sub>3</sub>)
        {
            stat<sub>4</sub>;
            stat<sub>5</sub>;
        }
        else
            stat<sub>6</sub>;
</div></div>else
    stat<sub>7</sub>;
</div>stat<sub>8</sub>;</code></pre>
</div>

Upvotes: 3

Views: 1482

Answers (2)

i alarmed alien
i alarmed alien

Reputation: 9530

If you want to mark up your code with the code element, but you want a particular presentation style, use elements like div to set the arrangement of the elements, and then <code> to mark up the code itself. For your html, this would be:

<div class="codeDiv black">
<code>stat<sub>0</sub>;
</code>
<div class="back-red codeBoxMargin">
<code>if (expr<sub>1</sub>)
</code>
<div class="back-green codeBoxMargin">
<code>  if (expr<sub>2</sub>)
    {
        stat<sub>1</sub>;
        stat<sub>2</sub>;
    }
    else
</code>
<div class="back-blue codeBoxMargin">
<code>       if (expr<sub>3</sub>)
        {
            stat<sub>4</sub>;
            stat<sub>5</sub>;
        }
        else
            stat<sub>6</sub>;
</code></div></div><code>else
    stat<sub>7</sub>;
</code>
</div><code>stat<sub>8</sub>;</code>
</div>

NB: I have removed the <pre> tags!

You can then set the whitespace to be preserved using the css declaration code { white-space: pre; } and set your font to an appropriate monospace font.

code {
    white-space: pre;
    font: 1em/1.5 Menlo, Consolas, 'DejaVu Sans Mono', Monaco, monospace; /* or whatever */
}

Here's the JSFiddle.

<code> is an inline element meant for marking up spans of text within block-level elements like <div>, <p>, and so on. While most browsers will happily render your original html, it would be syntactically incorrect.

Upvotes: 2

lxg
lxg

Reputation: 13107

code is an inline element, while div is a block element. Block elements must not appear inside inline elements.

If you want to have a div inside a preformatted container, use pre. Note, however, that pre by default shows line-breaks as-is. Or use a span element inside code (as proposed by Lowe Bäckström in a comment).

Upvotes: 4

Related Questions