When I have code nested like this (taken straight from prism's front page), the pre tag also gets the language-css
class when I inspect the DOM in my browser. Here is the code as I've written it:
<pre><code class="language-css">p { color: red }</code></pre>
When I inspect it in the browser it is like this:
<pre class="language-css"><code class="language-css">p { color: red }</code></pre>
My example is slightly different (different language than CSS), but the structure of elements is very close for me <pre><code/><textarea/></pre>
If I either 1) remove the prism.js line in my index.html (thus removing prism.js functionality) or 2) remove the class from the <code>
tag (also removing the functionality for this example) the <pre>
tag will no longer have language-css
when I inspect it in Firefox.
Adding the class to both elements allows theme authors to distinguish between code blocks (<pre><code>
) and inline code (<p><code>
). For example, the default Prism theme contains these three rules:
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #f5f2f0;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
white-space: normal;
}
As a use case, some theme authors may want to apply different styles to code blocks based on their language. For example, on my site (in places such as the About page), I've added labels to my code blocks using generated content — this can be added to the default theme like so:
@import url('https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism.min.css');
pre[class*="language-"] {
position: relative;
padding-top: 2.5em;
}
pre[class*="language-"]::before {
display: block;
position: absolute;
top: 0;
left: 0;
font-family: sans-serif;
background-color: #fff;
border-bottom-right-radius: 0.5em;
padding: 0.25em 0.5em;
}
pre.language-html::before { content: 'HTML'; }
pre.language-css::before { content: 'CSS'; }
<pre><code class="language-html"><!DOCTYPE html>
<title>HTML</title>
<p>Prism example</code></pre>
<pre><code class="language-css">pre[class*="language-"] {
position: relative;
padding-top: 1.5em;
}
pre[class*="language-"]::before {
display: block;
font: 0.8em sans-serif;
position: absolute;
top: 0.5em;
left: 0.5em;
}
pre.language-html::before { content: 'HTML'; }
pre.language-css::before { content: 'CSS'; }</code></pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/components/prism-markup.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/components/prism-css.min.js"></script>