In html suppose I have two tags in hand <code>
and <pre>
and I want to write preformatted code then does the ordering of these tags matter? E.g. Are the following equivalent?
<!DOCTYPE html>
<html>
<body>
<p>Code example:</p>
<pre><code>var person = {
firstName:"John2",
lastName:"Doe"
}</code></pre>
</body>
</html>
Now I nest <pre>
inside the <code>
tag,
<!DOCTYPE html>
<html>
<body>
<p>Code example:</p>
<code><pre>var person = {
firstName:"John2",
lastName:"Doe"
}</pre></code>
</body>
</html>
Would there be any technical difference between the above two approaches?
Addendum: I also don't understand how is the html code being translated here. In the first version The text inside the code tags should be translated into something which doesn't retain extra white spaces and line-breaks so the pre tags should see the output of code tags and should not render extra white spaces and line breaks.
And in the second case the output of pre tags should be given to code tags. Now the code tags will see the preserved extra white spaces and line breaks but the output of code tags should not retain them because that is what the code tag does; it gives up extra white spaces and line breaks.
For html elements in general, there are 2 major groups, inline elements, for example
<span> <code> <a> <img> <b>
and block elements
<div> <pre> <p> <h1> <ul>
To be nested valid, a block element can contain
and an inline element can contain
There are exceptions, though I will not bring them up here.
Also, if one would put a block element inside an inline, it will often still show the same output.
Why? ... Most browsers will try to interpret what one did and try to "fix it and make it work anyway".
So to answer your question
does the ordering of these tags matter?
Yes, in general, block elements are not allowed inside inline elements, but there can be other reasons and exceptions as well.
Regarding your question (comment)
Which is translated first? The code inside <code> or the <pre> tags are given higher priority?
Short answer, the inner element's property, when set, either explicit or predefined, overrides the outer element's equal property.
So in your case, the pre
element's white-space property is set, as default, to white-space: pre
and as the white-space
property is inherited by default, the code
uses that value, hence the output looks the same as for the pre
element.
But if we were to explicit set the white-space
property on the code
element, it will behave as you might expect, with no line breaks etc.
#reset code {
white-space: normal;
}
<div>
<p>Example: inheritence of property</p>
<pre>
<code>
var person = {
firstName:"John2",
lastName:"Doe"
}
</code>
</pre>
</div>
<hr>
<div id="reset">
<p>Example: explicit set property</p>
<pre>
<code>
var person = {
firstName:"John2",
lastName:"Doe"
}
</code>
</pre>
</div>