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.
<head>
<meta charset="UTF-8">
<title>Автоматическое оглавление (содержание) для статей насайте</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<header class="container">
<div>
ШАПКА
</div>
</header>
<main class="container entry-content">
<article class="article">
<h1>Заголовок</h1>
<p>Контент...</p>
<h2>Раздел 1</h2>
<p>Контент...</p>
<h2>Раздел 2</h2>
<p>Контент...</p>
<h2>Раздел 3</h2>
<p>Контент...</p>
<h2>Раздел 4</h2>
<p>Контент...</p>
<p>Контент...</p>
</article>
<div class="toc-label"></div>
</main>
<footer class="container">
<div>
ПОДВАЛ
</div>
</footer>
</body>
.container {
max-width: 800px;
margin-left: auto;
margin-right: auto;
}
header,
footer {
padding-left: 15px;
padding-right: 15px;
}
header>div,
footer>div,
h1 {
padding-top: 15px;
padding-bottom: 15px;
font-size: 22px;
text-align: center;
}
header>div {
background-color: #ffecb3;
}
h1 {
background-color: #b2ebf2;
}
footer>div {
background-color: #e1bee7;
}
main {
display: flex;
flex-wrap: wrap;
}
article {
flex: 0 0 100%;
max-width: 100%;
width: 100%;
padding-left: 15px;
padding-right: 15px;
margin-top: 15px;
order: 2;
}
#title-content {
flex: 0 0 100%;
max-width: 100%;
width: 100%;
padding-left: 15px;
padding-right: 15px;
margin-top: 15px;
order: 1;
}
@media (min-width: 500px) {
article {
flex: 0 0 60%;
max-width: 60%;
order: 1;
}
#title-content {
flex: 0 0 40%;
max-width: 40%;
margin-bottom: 15px;
order: 2;
}
}
.article-contents {
background-color: #dcedc8;
padding: 15px;
position: sticky;
top: 15px;
}
h1 {
font-size: 20px;
margin-top: 0;
margin-bottom: 0;
}
h2 {
font-size: 18px;
}
p {
min-height: 500px;
padding: 15px;
background-color: #eee;
}
li.active {
font-weight: bold;
}
a {
text-decoration: none;
color: #007bff;
}
a:hover {
text-decoration: none;
color: #007bff;
}
/* Блок оглавления */
html {
scroll-behavior: smooth;
/* Плавный переход к якорям */
}
.toc-label {
height: 100%;
margin-top: 15px;
position: sticky;
/* Прилипающий блок */
top: 15px;
/* Зазор прилипающего блока */
}
.sticky-block {
position: sticky;
top: 30px;
}
.toc-block {
padding: 1.5rem;
line-height: 1;
border: 1px solid #ebebeb;
border-radius: 3px;
position: relative;
}
.toc-block ul {
list-style: none;
padding: 0;
margin: 0;
}
.toc-block > ul {
height: 100%;
transition: opacity 0.5s ease-out, height 0.5s ease 0.5s;
}
.toc-block > ul.close {
opacity: 0;
height: 0;
transition: opacity 0.5s ease-out, height 0.5s ease 0.5s;
}
:target {
/* Отступ к прокручиваемому якорю */
scroll-margin-top: 2rem;
padding-top: 50px;
margin-top: -50px;
}
.toc-block ul li {
font-size: 0.9rem;
line-height: 1.2;
margin-top: 10px;
}
.toc-block ul ul {
margin-left: 10px;
}
.toc-block li a {
text-decoration: none;
opacity: 0.65;
}
.toc-block li a.highlight {
opacity: 1;
display: list-item;
list-style-type: disc;
}
.toc-close-open {
text-align: right;
position: absolute;
bottom: 5px;
right: 5px;
line-height: 1;
cursor: pointer;
font-size: 0.9rem;
opacity: 0.7;
transition: .5s;
}
.toc-close-open:hover {
opacity: 1;
}
@media (max-width: 757px) {
.toc-label {
position: fixed !important;
top: auto;
right: 0;
left: 0;
bottom: 0;
background: azure;
z-index: 1000;
height: unset;
}
.toc-block {
border: none;
padding: 0.5rem 1rem;
}
.toc-block ul li {
font-size: 1rem;
}
}
document.addEventListener('DOMContentLoaded', function() {
/* Создание содержания */
let
rollUp = 'Свернуть',
expand = 'Развернуть',
output = document.createDocumentFragment(),
entryContent = document.querySelector('.entry-content'),
headers2 = entryContent.querySelectorAll('h2'), // Ищем заголовки только в блоке с контентом
headers3 = entryContent.querySelectorAll('h3'),
wrapper = document.createElement('nav'),
title = document.createElement('div'),
ul = document.createElement('ul'),
divCloseOpen = document.createElement('div'), // div для кнопки скрыть Содержимое
tocLabel = document.querySelector('.toc-label'); // Нужно разместить элемент с этим классом где нужно вывести TOC
wrapper.classList.add('toc-block');
title.style.fontWeight = 'bold';
title.textContent = 'Содержание:';
output.appendChild(wrapper);
wrapper.appendChild(title);
wrapper.appendChild(ul);
divCloseOpen.classList.add('toc-close-open');
divCloseOpen.innerHTML = rollUp;
ul.after(divCloseOpen);
/* Добавляем один класс для всех h2 и h3 и получаем все заголовки */
headers2.forEach(function(item, index) {
item.classList.add('header-toc');
});
headers3.forEach(function(item, index) {
item.classList.add('header-toc');
});
let allHeaders = document.querySelectorAll('.header-toc');
allHeaders.forEach(function(item, index) {
let
li = document.createElement('li'),
link = document.createElement('a');
if (item.id === '') {
item.id = 'id-' + index;
}
link.href = '#' + item.id;
link.textContent = item.textContent;
li.appendChild(link);
if (item.localName == 'h3') {
let tocBlockUl = wrapper.querySelector('.toc-block ul');
if (tocBlockUl.lastChild.lastChild.localName == 'ul') {
tocBlockUl.lastChild.lastChild.appendChild(li);
} else {
let ul_h3 = document.createElement('ul');
ul_h3.appendChild(li);
ul.lastChild.appendChild(ul_h3);
}
} else {
ul.appendChild(li);
}
});
tocLabel.appendChild(output);
// Массив ссылок в блоке toc (оглавление)
var toc;
// Массив контента (ссылки относятся к контенту)
var content = [];
// Вызов функции prepare после загрузки HTML
prepare();
sync();
/* Эта функция получает все ссылки и содержимое toc (оглавление) и сохраняет тему */
function prepare() {
// Получить все ссылки toc (оглавление)
toc = document.querySelectorAll('.toc-block a');
// Получить контент, чтобы ссылка ссылалась на него
toc.forEach(function(link) {
var id = link.getAttribute("href");
var element = document.querySelector(id);
content.push(element);
});
// Синхронизировать toc (оглавление) с частью контента, которая видна в окне просмотра при прокрутке
window.addEventListener("scroll", sync, false);
}
/*
Эта функция проверяет, виден ли элемент в области просмотра
@argument {String} элемент, который нам нужно проверить
@returns true, если элемент виден в окне просмотра, иначе вернуть false
*/
function isElementInViewport(element) {
// Получить позицию элемента
var rect = element.getBoundingClientRect();
// Вернуть true, если часть элемента видна
return (rect.bottom >= 0 && rect.top <= (window.innerHeight || document.documentElement.clientHeight));
// Пока нам нужно проверить, весь ли элемент виден в окне просмотра
// return (rect.top >= 0 &&
// rect.bottom <= (window.innerHeight || document.documentElement.clientHeight));
}
/* Эта функция выделяет ссылки toc (оглавление), которые видны в области просмотра */
function sync() {
// Проверить весь контент
for (var i = 0; i < content.length; i++) {
// Если контент виден, добавить класс highlight, иначе убрать highlight
if (isElementInViewport(content[i])) {
toc[i].classList.add('highlight');
} else {
toc[i].classList.remove('highlight');
}
}
}
/* Функция свернуть Содержимое */
var tocCloseOpen = document.querySelector('.toc-close-open');
tocCloseOpen.addEventListener('click', hiddenCloseClick);
function hiddenCloseClick(elem) {
if (elem.target.textContent == rollUp) {
elem.target.textContent = expand;
} else {
elem.target.textContent = rollUp;
}
let x = document.querySelector('.toc-block > ul');
x.classList.toggle('close');
};
/* Функция делает сайдбар липким если есть Содержание */
var tocBlock = document.querySelector('.toc-block');
var sidebar = document.querySelector('.toc-label');
if (window.screen.width > 757) {
if (tocBlock) {
sidebar.classList.add('sticky-block');
}
} else {
let tocCloseOpen = document.querySelector('.toc-close-open');
// Если есть Содержание то сварачиваем его для мобильной версии
if (tocCloseOpen) {
if (tocCloseOpen.textContent == rollUp) {
tocCloseOpen.textContent = expand;
} else {
tocCloseOpen.textContent = rollUp;
}
let x = document.querySelector('.toc-block > ul');
x.classList.toggle('close');
}
}
}, false); // конец addEventListener DOMContentLoaded
Also see: Tab Triggers