HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<code-block class="language-css line-numbers" data-line="2">
<pre>
html {
--brandColor: red;
background: var(--brandColor);
}
body {
text-rendering: optimizeSpeed;
height: 100vh;
margin: 0;
font-family: "Georgia", serif;
}
</pre>
</code-block>
<code-block class="language-html line-numbers" data-line="2">
<pre>
<div class="card">
<h2>Cool.</h2>
</div>
</pre>
</code-block>
<code-block class="language-javascript line-numbers" data-line="2">
<pre>
const name = "Chris Coyier";
console.log(name);
</pre>
</code-block>
<template id="code-block-template">
<style>
pre[class*="language-"] {
background: #111;
color: white;
font-family: monospace;
font-size: 120%;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.6;
-moz-tab-size: 2;
-o-tab-size: 2;
tab-size: 2;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
border-radius: .5em;
margin: .5em 0;
overflow: auto;
padding: 1em;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: hsl(0, 0%, 47%);
}
.token.punctuation {
opacity: .7;
}
.token.namespace {
opacity: .7;
}
.token.tag,
.token.boolean,
.token.number,
.token.deleted {
color: hsl(14, 58%, 55%); /* #CF6A4C */
}
.token.keyword,
.token.property,
.token.selector,
.token.constant,
.token.symbol,
.token.builtin {
color: hsl(53, 89%, 79%); /* #F9EE98 */
}
.token.attr-name,
.token.attr-value,
.token.string,
.token.char,
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string,
.token.variable,
.token.inserted {
color: hsl(76, 21%, 52%); /* #8F9D6A */
}
.token.atrule {
color: hsl(218, 22%, 55%); /* #7587A6 */
}
.token.regex,
.token.important {
color: hsl(42, 75%, 65%); /* #E9C062 */
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
/* Markup */
.language-markup .token.tag,
.language-markup .token.attr-name,
.language-markup .token.punctuation {
color: hsl(33, 33%, 52%); /* #AC885B */
}
/* Make the tokens sit above the line highlight so the colours don't look faded. */
.token {
position: relative;
z-index: 1;
}
.line-highlight {
background: hsla(0, 0%, 33%, 0.25); /* #545454 */
background: linear-gradient(to right, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */
border-bottom: 1px dashed hsl(0, 0%, 33%); /* #545454 */
border-top: 1px dashed hsl(0, 0%, 33%); /* #545454 */
left: 0;
line-height: inherit;
margin-top: 0.75em; /* Same as .prism’s padding-top */
padding: inherit 0;
pointer-events: none;
position: absolute;
right: 0;
white-space: pre;
z-index: 0;
}
.line-highlight:before,
.line-highlight[data-end]:after {
background-color: hsl(215, 15%, 59%); /* #8794A6 */
border-radius: 999px;
box-shadow: 0 1px white;
color: hsl(24, 20%, 95%); /* #F5F2F0 */
content: attr(data-start);
font: bold 65%/1.5 sans-serif;
left: .6em;
min-width: 1em;
padding: 0 .5em;
position: absolute;
text-align: center;
text-shadow: none;
top: .4em;
vertical-align: .3em;
}
.line-highlight[data-end]:after {
bottom: .4em;
content: attr(data-end);
top: auto;
}
pre[data-line] {
position: relative;
padding: 1em 0 1em 3em;
}
.line-highlight {
position: absolute;
left: 0;
right: 0;
padding: inherit 0;
margin-top: 1em; /* Same as .prism’s padding-top */
background: hsla(24, 20%, 50%,.08);
background: linear-gradient(to right, hsla(24, 20%, 50%,.1) 70%, hsla(24, 20%, 50%,0));
pointer-events: none;
line-height: inherit;
white-space: pre;
}
.line-highlight:before,
.line-highlight[data-end]:after {
content: attr(data-start);
position: absolute;
top: .4em;
left: .6em;
min-width: 1em;
padding: 0 .5em;
background-color: hsla(24, 20%, 50%,.4);
color: hsl(24, 20%, 95%);
font: bold 65%/1.5 sans-serif;
text-align: center;
vertical-align: .3em;
border-radius: 999px;
text-shadow: none;
box-shadow: 0 1px white;
}
.line-highlight[data-end]:after {
content: attr(data-end);
top: auto;
bottom: .4em;
}
.line-numbers .line-highlight:before,
.line-numbers .line-highlight:after {
content: none;
}
pre[class*="language-"].line-numbers {
position: relative;
padding-left: 3.8em;
counter-reset: linenumber;
}
pre[class*="language-"].line-numbers > code {
position: relative;
white-space: inherit;
}
.line-numbers .line-numbers-rows {
position: absolute;
pointer-events: none;
top: -0.13em; /* wtf */
left: -3.8em;
width: 3em; /* works for line-numbers below 1000 lines */
border-right: 1px solid #999;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.line-numbers-rows > span {
pointer-events: none;
display: block;
counter-increment: linenumber;
}
.line-numbers-rows > span::before {
content: counter(linenumber);
color: #999;
display: block;
padding-right: 0.8em;
text-align: right;
}
#copy-button {
position: absolute;
top: 5px;
right: 5px;
}
</style>
</template>
/*
Code Block Web Component
1) ✅ Basic styles (pulls `styles` global from another Pen)
2) ✅ Syntax Highlight (assumes global `Prism`)
3) ✅ Click to copy (Native JavaScript)
4) ✅ Optional Line numbers (Prism feature)
6) ✅ whitespace top/bottom trimming
TODO
[ ] Is there a way to avoid the <pre> in the custom element but still handle whitespace OK? Or is <pre> super magical and it's the only practial way to handle whitespace? Justin's doesn't seem to need it https://github.com/justinribeiro/code-block
[ ] Implement line highlighting feature from Prism (had trouble with styles).
[ ] Could this do entity escaping for you, so you didn't have to bother with that in the HTML? Or is that too weird because you wouldn't want the raw HTML sitting in the HTML to start with, in case the JS doesn't load? Maybe put HTML in <!-- comments
--> or is that too weird because what if you want to show comments?
*/
(function() {
class CodeBlockComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
bindEvents() {
const { shadowRoot } = this;
const copyButton = shadowRoot.querySelector('#copy-button');
copyButton.addEventListener("click", () => {
this.copyCode();
});
}
copyCode() {
const { shadowRoot } = this;
const codeNode = shadowRoot.querySelector('#code');
const range = document.createRange();
range.selectNode(codeNode);
window.getSelection().addRange(range);
try {
document.execCommand('copy');
} catch(err) {
console.warn('Oops, unable to copy');
}
}
connectedCallback() {
const { shadowRoot } = this;
const styles = document.querySelector("#code-block-template").innerHTML;
let lang = this.classList.value;
lang = lang.replace("language-", "");
const trimmed = this.innerHTML.trim();
let lineNumbersClass = "";
if (this.classList.contains("line-numbers")) {
lineNumbersClass = "line-numbers";
}
// Line Highlighting would be something like this.
// let lineHighlights = "";
// if (this.dataset.line) {
// lineHighlights = this.dataset.line;
// }
// Plus data-line="${lineHighlights} on the <pre>
const template = `
<div>
${styles}
<pre class="${lineNumbersClass} ${this.classList}" id="pre"><code id="code">${trimmed}</code><button id="copy-button">Copy</button></pre>
</div>
`;
const placeholder = document.createElement('div');
placeholder.insertAdjacentHTML('afterbegin', template);
const node = placeholder.firstElementChild;
shadowRoot.appendChild(node);
// We could highlight it _before_ injecting with a different Prism function, but I'm not sure it does plugins then, like line numbers. Should check.
Prism.highlightAllUnder(shadowRoot);
this.bindEvents();
}
}
customElements.define('code-block', CodeBlockComponent);
})();
Also see: Tab Triggers