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.
<div id="root"/>
body {
font-family: sans-serif;
line-height: 1.6;
background-color: #1F2233;
color: #D8DEE9;
}
.container {
max-width: 1050px;
margin: 0 auto;
display: flex;
}
main {
max-width: 800px;
background-color: #161822;
padding: 16px;
border-radius: 8px;
margin-left: 8px;
}
nav {
width: 220px;
min-width: 220px;
padding: 16px;
margin: 8px;
align-self: flex-start;
position: -webkit-sticky; /* Safari */
position: sticky;
top: 48px;
max-height: calc(100vh - 70px);
overflow: auto;
}
@media screen and (max-width: 900px) {
nav {
display: none;
}
}
a {
color: #A6ACC9;
text-decoration: none;
}
li.active > a {
color: white;
}
li > a:hover {
color: white;
}
/* Gives a little bit of buffer when header is navigated to */
h2, h3 {
padding-top: 16px;
margin-top: -16px;
}
/**
* This renders an item in the table of contents list.
* scrollIntoView is used to ensure that when a user clicks on an item, it will smoothly scroll.
*/
const Headings = ({ headings, activeId }) => (
<ul>
{headings.map((heading) => (
<li key={heading.id} className={heading.id === activeId ? "active" : ""}>
<a
href={`#${heading.id}`}
onClick={(e) => {
e.preventDefault();
document.querySelector(`#${heading.id}`).scrollIntoView({
behavior: "smooth"
});
}}
>
{heading.title}
</a>
{heading.items.length > 0 && (
<ul>
{heading.items.map((child) => (
<li
key={child.id}
className={child.id === activeId ? "active" : ""}
>
<a
href={`#${child.id}`}
onClick={(e) => {
e.preventDefault();
document.querySelector(`#${child.id}`).scrollIntoView({
behavior: "smooth"
});
}}
>
{child.title}
</a>
</li>
))}
</ul>
)}
</li>
))}
</ul>
);
/**
* Dynamically generates the table of contents list, using any H2s and H3s it can find in the main text
*/
const useHeadingsData = () => {
const [nestedHeadings, setNestedHeadings] = React.useState([]);
React.useEffect(() => {
const headingElements = Array.from(
document.querySelectorAll("main h2, main h3")
);
// Created a list of headings, with H3s nested
const newNestedHeadings = getNestedHeadings(headingElements);
setNestedHeadings(newNestedHeadings);
}, []);
return { nestedHeadings };
};
const getNestedHeadings = (headingElements) => {
const nestedHeadings = [];
headingElements.forEach((heading, index) => {
const { innerText: title, id } = heading;
if (heading.nodeName === "H2") {
nestedHeadings.push({ id, title, items: [] });
} else if (heading.nodeName === "H3" && nestedHeadings.length > 0) {
nestedHeadings[nestedHeadings.length - 1].items.push({
id,
title
});
}
});
return nestedHeadings;
};
const useIntersectionObserver = (setActiveId, activeId) => {
const headingElementsRef = React.useRef({});
React.useEffect(() => {
const callback = (headings) => {
headingElementsRef.current = headings.reduce((map, headingElement) => {
map[headingElement.target.id] = headingElement;
return map;
}, headingElementsRef.current);
// Get all headings that are currently visible on the page
const visibleHeadings = [];
Object.keys(headingElementsRef.current).forEach((key) => {
const headingElement = headingElementsRef.current[key];
if (headingElement.isIntersecting) visibleHeadings.push(headingElement);
});
const getIndexFromId = (id) =>
headingElements.findIndex((heading) => heading.id === id);
// If there is only one visible heading, this is our "active" heading
if (visibleHeadings.length === 1) {
setActiveId(visibleHeadings[0].target.id);
// If there is more than one visible heading,
// choose the one that is closest to the top of the page
} else if (visibleHeadings.length > 1) {
const sortedVisibleHeadings = visibleHeadings.sort(
(a, b) => getIndexFromId(a.target.id) > getIndexFromId(b.target.id)
);
setActiveId(sortedVisibleHeadings[0].target.id);
}
// If there are no visible headings, and we are scrolling back up, we want to make sure
// the correct header is highlighted.
// Shoutout to Heisman2 for this addition, and Ky Wildermuth for originally suggesting it!
if (visibleHeadings.length === 0) {
const activeElement = headingElements.find((el) => el.id === activeId);
const activeIndex = headingElements.findIndex(
(el) => el.id === activeId
);
const activeIdYcoord = activeElement?.getBoundingClientRect().y;
if (activeIdYcoord && activeIdYcoord > 150 && activeIndex !== 0) {
setActiveId(headingElements[activeIndex - 1].id);
}
}
};
const observer = new IntersectionObserver(callback, {
root: document.querySelector("iframe"),
rootMargin: "500px"
});
const headingElements = Array.from(document.querySelectorAll("h2, h3"));
headingElements.forEach((element) => observer.observe(element));
return () => observer.disconnect();
}, [setActiveId, activeId]);
};
/**
* Renders the table of contents.
*/
const TableOfContents = () => {
const [activeId, setActiveId] = React.useState();
const { nestedHeadings } = useHeadingsData();
useIntersectionObserver(setActiveId, activeId);
return (
<nav aria-label="Table of contents">
<Headings headings={nestedHeadings} activeId={activeId} />
</nav>
);
};
const DummyText =
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
const App = () => {
return (
<div className="container">
<main>
<h2 id="initial-header">Initial header</h2>
<p>{DummyText}</p>
<h2 id="second-header">Second header</h2>
<p>{DummyText}</p>
<h3 id="third-header">Third header</h3>
<p>{DummyText}</p>
<p>{DummyText}</p>
<h2 id="fourth-header">Fourth header</h2>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<p>{DummyText}</p>
<h3 id="fifth-header">Fifth header</h3>
<p>{DummyText}</p>
<p>{DummyText}</p>
</main>
<TableOfContents />
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
Also see: Tab Triggers