¿Por qué HTML5 recomienda poner el elemento de código dentro de pre?

The HTML5 documentation recommends poniendo el code elemento dentro del pre element, but I don't understand how this is better or more semantic than just using the code element and CSS. In their own example:

<pre><code class="language-pascal">var i: Integer;
begin
   i := 1;
end.</code></pre>

Could also be written (Making some assumptions about the browser's defaults for pre):

<style>
code {
    display: block;
    white-space: pre;
}
</style><code class="language-pascal">var i: Integer;
begin
   i := 1;
end.</code>

Incluso si el pre is there to distinguish a code bloquear from an inline string of code, I don't see it being a more semantic choice than specifying the block-ness de los code en una clase.

Is there a specific reason the pre is recommended over a CSS solution?

preguntado el 31 de julio de 12 a las 15:07

porque <code> while does apply a fixed-width font, it does not apply any line-break honoring as <pre> will. e.g. applying <code> to formatted code will break the formatting. This is somewhat of an oversight in the original definition of <code>, and now we're stuck with it for backwards compatibility. -

The documentation don't "recommend" it, it just shows it as an example. "[the example] shows how a block of code podría be marked up using the pre y code elementos. "-

@MarcB I don't think it's an oversight. As I said in my question, code is also useful for inline code strings. But that doesn't make pre a better solution than CSS for block formatting. -

No quieres decir white-space: pre; in the css snippet? -

@kojiro deep breaths, think of a calm blue ocean. also, add a dash to white-space? :) -

4 Respuestas

<code> represents only a "fragment of computer code". It was originally thought for simple code snippets like i++ or <code>.

<pre> "represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements". It's original purpose was nothing more than exactly this: provide a text in the same way it was given by the author, e.g.

+----------------------------------+
|                                  |
| WARNING! PREFORMATED TEXT AHEAD! |                      =o=
|                               __;                                  ~^
+----------------TT------------°
                 ||    _____________    _____________________
                 ||    | TO GRANDMA  >  | TOTALLY NOT A TRAP  > 
  oÖo            ||    |°°°°°°°°°°°°    °°°°°°°°°°°°°°°°°°°°°          
   |  ö          ||    |                |      .mm,                    
~"""~"""~"""~"""~"""~"""~~"""~"""~"""~"""~"""~"""~"""~"""~"""~""..MWMWc...~"""~""

You don't need to use each with each other. <pre> has its own roles, like <code> has its own. However, <pre> is a way to signalize that the white-space in the given fragment is important, a role that <code> no se encuentra.

However, back to your question: note the exacto fraseología:

The following example shows how a block of code podría be marked up using the pre y code elementos.

<pre><code class="language-pascal">var i: Integer;
begin
   i := 1;
end.</code></pre>

En ese ejemplo se utiliza una clase para indicar el idioma utilizado.

Dice podríano, debemos. You're free to do this how you want. It's not recommended by the W3C in any way, however, I personally recommend you to use <pre><code>....

Explicación adicional

Whenever white-space is part of your code and the structure of your code, you should state that this structure should be kept. As the structure in code is given by typographic conventions (tabs, linefeeds, spaces) I personalmente te recomiendo que uses <pre><code>, even if it's arguably more code and another node in the DOM. But whenever missing white-space will render your code imperfect it's necessary.

Apart from that you can easily differ between inline code and code-blocks without checking element.className, and some JS syntax highlighter work pretty well with <pre><code>... and strip the <code> automáticamente.

Also, if you use a general rule for <code> con white-space:pre;, you cannot use it for inline snippets without additional classes. If you were to create a class instead, you've won nothing compared to <pre><code>.

Referencias

  • W3C: HTML5: 4.5.12 The code element (W3C Recommendation 28 October 2014)

    La opción code elementos representa a fragment of computer code. This could be an XML element name, a file name, a computer program, or any other string that a computer would recognize.

  • W3C: HTML5: 4.4.3 The pre element (W3C Recommendation 28 October 2014)

    La opción pre elementos representa a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.

respondido 05 nov., 17:17

This is a well-thought-out answer, but I'll pose the same followup I posed for Quentin: So then I should use pre for code with significant whitespace, and CSS for code where the whitespace is presentational? - kojiro

Whenever white-space is part of your code and the structure of your code, you should state that this structure should be kept. As the structure in code is given by typographic conventions (tabs, linefeeds, spaces) I personally recommend you to use <pre><code>, even if it's arguably more code and another node in the DOM. (Apart from that you can easily differ between inline code and blocks, and some JS syntax highlighter work only on <pre><code>... and strip the <code> automatically). - Zed

+1 If your goal is semantic markup, i agree with Zeta's recommendation, seeing as <pre> means preformatted and <code> means code fragment, when what you are marking up is preformatted code, using <pre><code> makes sense. If your goal is clean markup, I would go with the css white-space: pre; solución. - controlar

I write my programs with high degree of formatting. So writing <pre><code> kicks in my OCD. If I write the <code> in the next line, it will cause additional newline and spaces in the output. Couldn't I just write <pre> dentro <code>? Doesn't that make more sense, since its the actual computer-code that is pre-formatted? I can't see anyone recommending this... - Pantera negra

@BlackPanther: code espera contenido de redacción, pero pre isn't phrasing content. So from a standard point of view, it's not valid (in HTML4 terms: you cannot put a block element in an inline element). Also, while HTML5 parece to ignore whitespace at many points, it often doesn't. Space between elements leads to additional nodes in the DOM (at least in Gecko). - Zed

CSS is for presentation.

White space is significant (not presentational) in many programming languages.

Respondido 31 Jul 12, 15:07

It should also be noted that even in programming languages that white space isn't es requerida for (technically speaking), it is necessary in order for humans to read it easily. - 0b10011

@FabianBarney, umm... yeah, I know. That's what I said "...even in programming languages that white space isn't es requerida for...". I nunca said white space wasn't technically required for any programming languages. - 0b10011

@bfrohs Oh sry, I misunderstood you in the first place. +1 - Fabián Barney

So then I should use pre tags for code with significant whitespace, and CSS for code where the whitespace is presentational? - kojiro

This answer makes me wonder whether <pre> is semantic markup at all, or rather like <b>, <i> (i.e., a purely representational left-over of early HTML versions). - stakx - ya no contribuye

To represent a block of computer code, the pre element can be used with a code element;

To represent a block of computer output the pre element can be used with a samp element.

<pre><code> for block code that must not wrap. Use <code> for inline code that can wrap.

Line breaks and white spaces in the text enclosed within the <pre> tags is maintained as it is in the html document when displays on the browser.Browsers normally render <pre> text in a fixed-pitched font, with whitespace.

Respondido 31 Jul 12, 16:07

This doesn't really answer the OPs question, which was "el porqué the <pre> in the html5 example?" - controlar

he asked "Is there a specific reason the pre is recommended over a CSS solution?" In my knowledge i answered. - Prashobh

<pre> shows line breaks!

This prevent you using php function such as nl2br() or adding manually <br /> en cada final de línea.

Regards, Ghost

Respondido 31 Jul 12, 16:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.