Debian Codegraph @

docs/src/markdown/extensions/tabbed.md

raw
1 ---
2 icon: lucide/app-window
3 ---
4 [:octicons-file-code-24:][_tabbed]{: .source-link }
5
6 # Tabbed
7
8 /// tip | 9.10 New Approach to Tabs
9 9.10 has added a new approach to creating tabs. Checkout the new [Tab extension here](./blocks/plugins/tab.md)!
10 ///
11
12 ## Overview
13
14 /// new | New 7.0
15 Tabbed has been newly added in 7.0.
16 ///
17
18 Tabbed provides a syntax to easily add tabbed Markdown content. The Tabbed extension can be included in Python Markdown
19 by using the following:
20
21 ```py3
22 import markdown
23 md = markdown.Markdown(extensions=['pymdownx.tabbed'])
24 ```
25
26 ## Syntax
27
28 Tabs start with `===` to signify a tab followed by a quoted title. Consecutive tabs are grouped into a tab set.
29
30 ```text title="Tabs"
31 === "Tab 1"
32 Markdown **content**.
33
34 Multiple paragraphs.
35
36 === "Tab 2"
37 More Markdown **content**.
38
39 - list item a
40 - list item b
41 ```
42
43 /// html | div.result
44
45 === "Tab 1"
46 Markdown **content**.
47
48 Multiple paragraphs.
49
50 === "Tab 2"
51 More Markdown **content**.
52
53 - list item a
54 - list item b
55 ///
56
57 In the rare case that you want to follow two separate tab sets right after each other, you can explicitly mark the start
58 of a new tab set with `!`.
59
60 ````text title="Tab Breaks"
61 === "Tab 1"
62 Markdown **content**.
63
64 Multiple paragraphs.
65
66 === "Tab 2"
67 More Markdown **content**.
68
69 - list item a
70 - list item b
71
72 ===! "Tab A"
73 Different tab set.
74
75 === "Tab B"
76 ```
77 More content.
78 ```
79 ````
80
81 /// html | div.result
82
83 === "Tab 1"
84 Markdown **content**.
85
86 Multiple paragraphs.
87
88 === "Tab 2"
89 More Markdown **content**.
90
91 - list item a
92 - list item b
93
94 ===! "Tab A"
95 Different tab set.
96
97 === "Tab B"
98 ```
99 More content.
100 ```
101 ///
102
103 ## Tab Select
104
105 /// new | New 9.7
106 ///
107
108 If you'd like to force a tab to be selected, simply use `===+`, otherwise, the first tab will be selected by default.
109
110 ```text
111 === "Not Me"
112 Markdown **content**.
113
114 Multiple paragraphs.
115
116 ===+ "Select Me"
117 More Markdown **content**.
118
119 - list item a
120 - list item b
121
122 === "Not Me Either"
123 Another Tab
124 ```
125
126 /// note
127 If you are using JavaScript to track selected tabs across pages, or some other tab related feature that adjusts selected
128 tabs, it may interfere with the default selected tab. This is not an indication that there is a bug, but an indication
129 of incompatible features.
130 ///
131
132 ## Tab IDs
133
134 /// new | New 9.0
135 ///
136
137 By default, tabs generate IDs for each tab using the following template `__tabbed_<tab_set_number>_<tab_number>`. If it
138 is desired to implement jumping to a specific tab with more intuitive IDs, it may be preferable to generate IDs from
139 slugs. To do so, two [options](#options) are provided: `slugify` and `separator`.
140
141 /// tip
142 Jumping to tabs via IDs may require additional JavaScript to select the targeted tabs.
143 ///
144
145 If `slugify` is given a slug function (you can use any that [ship with Pymdownx Extensions](../extras/slugs.md)), the
146 Tabbed extension will generate IDs from the tab titles just like headers. `separator` allows for the specifying of the
147 word separator (`-` is the default).
148
149 If you'd like the slugs to be prefixed with the slug of the parent header, you can enable the `combine_header_slug`
150 option. If you had the following example, normally the header slug would be `header` and the content tab would have the
151 slug `tab`.
152
153 ```
154 # header
155
156 === "tab"
157 content
158 ```
159
160 With `combine_header_slug` enabled, the header slug would still be `header`, but now the content tab slug would be
161 `header-tab`.
162
163 /// new | New 10.1
164 `combine_header_slug` is new in 10.1
165 ///
166
167 ## Styling with CSS
168
169 In order to use tabbed blocks, some additional CSS is needed. You can check out the configuration below which will
170 show the CSS and the HTML it targets. Keep in mind that the CSS provided below is just the minimum needed to get you
171 started. You can tweak it and modify it to get it how you like it.
172
173 In general, tabbed controls are wrapped in a `#!html <div>` with the class `tabbed-set`. They contain an
174 `#!html <input>` with an ID of `__tabbed_<tab_set_number>_<tab_number>`. All the `#!html <input>` elements from a
175 specific tab set will use the name `__tabbed_<tab_set_number>`. Particularly, a user should be mindful of the ID to keep
176 from explicitly using a conflicting ID. Auto-generated slugs shouldn't conflict though.
177
178
179 /// settings | Tabbed Code Setup
180 This is a very basic setup. Tabs can be styled in different ways, but this shows how to get it functionally working.
181 Here we show what it visually looks like, what the generated HTML looks like, and what the CSS looks like.
182
183 === "Preview"
184 ![Tabbed Style](../images/tabbed-default.png)
185
186 === "HTML"
187 ```html
188 <div class="tabbed-set" data-tabs="1:3"><input checked="checked" id="__tabbed_1_1" name="__tabbed_1" type="radio" /><label for="__tabbed_1_1">Tab with a really long title 1</label><div class="tabbed-content">
189 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
190 magna non laborum proident id voluptate in cupidatat duis.</p>
191 </div>
192 <input id="__tabbed_1_2" name="__tabbed_1" type="radio" /><label for="__tabbed_1_2">Tab with a really long title 2</label><div class="tabbed-content">
193 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
194 magna non laborum proident id voluptate in cupidatat duis.</p>
195 </div>
196 <input id="__tabbed_1_3" name="__tabbed_1" type="radio" /><label for="__tabbed_1_3">Tab with a really long title 3</label><div class="tabbed-content">
197 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
198 magna non laborum proident id voluptate in cupidatat duis.</p>
199 </div>
200 </div>
201 ```
202
203 === "CSS"
204 //// collapse-code
205 ```css
206 /* General environment setup */
207 html {
208 background-color: black;
209 height: 100%;
210 }
211 body {
212 font-size: 120%;
213 width: 100%;
214 padding: 1em 2em;
215 margin: 0 auto;
216 background-color: white;
217 height: 100%;
218 }
219
220 /* Tab style starts here */
221 .tabbed-set {
222 position: relative;
223 display: flex;
224 flex-wrap: wrap;
225 margin: 1em 0;
226 border-radius: 0.1rem;
227 }
228
229 .tabbed-set > input {
230 display: none;
231 }
232
233 .tabbed-set label {
234 width: auto;
235 padding: 0.9375em 1.25em 0.78125em;
236 font-weight: 700;
237 font-size: 0.84em;
238 white-space: nowrap;
239 border-bottom: 0.15rem solid transparent;
240 border-top-left-radius: 0.1rem;
241 border-top-right-radius: 0.1rem;
242 cursor: pointer;
243 transition: background-color 250ms, color 250ms;
244 }
245
246 .tabbed-set .tabbed-content {
247 width: 100%;
248 display: none;
249 box-shadow: 0 -.05rem #ddd;
250 }
251
252 .tabbed-set input {
253 position: absolute;
254 opacity: 0;
255 }
256
257 .tabbed-set input:checked:nth-child(n+1) + label {
258 color: red;
259 border-color: red;
260 }
261
262 @media screen {
263 .tabbed-set input:nth-child(n+1):checked + label + .tabbed-content {
264 order: 99;
265 display: block;
266 }
267 }
268
269 @media print {
270 .tabbed-content {
271 display: contents;
272 }
273 }
274 ```
275 ////
276 ///
277
278 ## Linked Tabs
279
280 Some sites will link tabs across tab containers. The easiest way to explain this is by example. Click a tab below and
281 see how they seem linked:
282
283 === "Python"
284
285 === "JavaScript"
286
287 ===! "Python"
288
289 === "JavaScript"
290
291 People ask about how to get this functionality from time to time, and the answer is JavaScript. It is the only real way
292 to get such functionality. While this can be achieved with varying degrees of intelligence -- save preferences across
293 pages for example -- we've provided a very basic example of how to accomplish this below.
294
295 The function, when called, will setup click events for every tab. When clicked, it will look for tabs of the same name
296 on the page and ensure they also get selected. It works for the default style and the new [alternate style](#alternate-style).
297
298 ```js
299 const tabSync = () => {
300 const tabs = document.querySelectorAll(".tabbed-set > input")
301 for (const tab of tabs) {
302 tab.addEventListener("click", () => {
303 const current = document.querySelector(`label[for=${tab.id}]`)
304 const pos = current.getBoundingClientRect().top
305 const labelContent = current.innerHTML
306 const labels = document.querySelectorAll('.tabbed-set > label, .tabbed-alternate > .tabbed-labels > label')
307 for (const label of labels) {
308 if (label.innerHTML === labelContent) {
309 document.querySelector(`input[id=${label.getAttribute('for')}]`).checked = true
310 }
311 }
312
313 // Preserve scroll position
314 const delta = (current.getBoundingClientRect().top) - pos
315 window.scrollBy(0, delta)
316 })
317 }
318 }
319 ```
320
321 /// tip | Special Considerations
322 If you are combining this feature with something like ["tab select"](#tab-select), you may have to not link tabs on
323 initial page load to ensure the default is not overridden. The example above does not initiate tab linking on
324 initial page load, only registration of the event. Some may attempt to implement tab linkage such that selected tabs
325 are remembered across pages, special consideration would be required in such situations and is beyond the scope of
326 this simple example.
327 ///
328
329 ## Alternate Style
330
331 /// new | New 9.0
332 ///
333
334 /// warning | Experimental Feature
335 ///
336
337 The original idea behind the Tabbed extension was to provide a tabbed interface in Markdown that could be driven purely
338 by CSS. If JavaScript was disabled or unavailable, tab functionality would remain.
339
340 @squidfunk (Martin Donath), the author and maintainer of the [MkDocs Material theme][mkdocs-material], who originally
341 collaborated on the first Tabbed style, approached us again with a newer style.
342
343 The aim was to solve one big problem, namely that on narrower screen sizes (like mobile), tabs are broken onto separate
344 lines, like here for example.
345
346 ![Tabbed Style Narrow](../images/tabbed-default-narrow.png)
347
348 And this is indeed a real issue with the current style. The bonuses of the current style is that it needs absolutely no
349 JavaScript and is driven by CSS alone. It supports as many tabs as you can throw at it but the downside is that when all
350 the tabs do not fit on a single line, they'll wrap which is not aesthetically pleasing in all themes or interfaces.
351
352 So, a new style was proposed, and we once again worked to hammer out the details, and in the end, we think we have
353 something that is better in many ways. The new style works with only CSS and does not actually need any JavaScript to be
354 functional, but it is ideally enhanced with a little JavaScript. The reason why is that when too many tabs are on a
355 single line, you can overflow them with CSS and make the tab container scrollable. This can provide a much more
356 aesthetically pleasing interface, but there are two caveats though:
357
358 1. When tabs overflow, if you want a visual indicator that there are more tabs, it requires a little JavaScript.
359 2. The number of tabs is limited by how many tabs you define in the CSS.
360
361 As for the first point, this seems an acceptable restraint. When JavaScript is available, you will get a nice visual
362 indicator, but if JavaScript is ever not available, or disabled, tab functionality will still work, just without the
363 indicators.
364
365 As for the second point, this also seems acceptable as most pages will usually have some upper limit of tabs that are
366 ever used. Pages can become quite cluttered when using too many tabs, and it seems reasonable that most would limit them
367 to some practical number.
368
369 /// settings | Alternate Tabbed Code Setup
370 The example below styles the tabs, adds indicators that work as buttons to navigate to the next tab when the there
371 are overflowed tabs, and scrolls tabs into view smoothly.
372
373 === "Preview"
374 ![Tabbed Style Alternate](../images/tabbed-alternate.png)
375
376 === "HTML"
377 ```html
378 <div class="tabbed-set tabbed-alternate" data-tabs="1:3"><input checked="checked" id="__tabbed_1_1" name="__tabbed_1" type="radio" /><input id="__tabbed_1_2" name="__tabbed_1" type="radio" /><input id="__tabbed_1_3" name="__tabbed_1" type="radio" /><div class="tabbed-labels"><label for="__tabbed_1_1">Tab with a really long title 1</label><label for="__tabbed_1_2">Tab with a really long title 2</label><label for="__tabbed_1_3">Tab with a really long title 3</label></div>
379 <div class="tabbed-content">
380 <div class="tabbed-block">
381 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
382 magna non laborum proident id voluptate in cupidatat duis.</p>
383 </div>
384 <div class="tabbed-block">
385 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
386 magna non laborum proident id voluptate in cupidatat duis.</p>
387 </div>
388 <div class="tabbed-block">
389 <p>Lorem ipsum ullamco ea aute do sint cupidatat elit nostrud exercitation dolore culpa aliquip nisi commodo nisi qui
390 magna non laborum proident id voluptate in cupidatat duis.</p>
391 </div>
392 </div>
393 </div>
394 ```
395
396 === "CSS"
397 //// collapse-code
398 ```css
399 /* General environment setup */
400 html {
401 background-color: black;
402 height: 100%;
403 }
404 body {
405 font-size: 120%;
406 width: 20em;
407 padding: 1em 2em;
408 margin: 0 auto;
409 background-color: white;
410 height: 100%;
411 }
412
413 /* Tab style starts here */
414 .tabbed-alternate {
415 position: relative;
416 display: flex;
417 flex-wrap: wrap;
418 flex-direction: column;
419 margin: 1em 0;
420 border-radius: 0.1rem;
421 }
422
423 .tabbed-alternate > input {
424 display: none;
425 }
426
427 .tabbed-labels {
428 display: flex;
429 width: 100%;
430 overflow: auto;
431 box-shadow: 0 -0.1rem #ddd inset;
432 scrollbar-width: none;
433 }
434 .tabbed-labels::-webkit-scrollbar {
435 display: none;
436 }
437 .tabbed-labels > label {
438 width: auto;
439 padding: 0.9375em 1.25em 0.78125em;
440 font-weight: 700;
441 font-size: 0.84em;
442 white-space: nowrap;
443 border-bottom: 0.1rem solid transparent;
444 scroll-snap-align: start;
445 border-top-left-radius: 0.1rem;
446 border-top-right-radius: 0.1rem;
447 cursor: pointer;
448 transition: background-color 250ms, color 250ms;
449 }
450 .tabbed-labels > label:hover {
451 color: red;
452 }
453
454 .tabbed-labels.tabbed-scroll-left::before {
455 display: inline-block;
456 font-size: 0.9em;
457 position: absolute;
458 top: 0.75em;
459 left: 0;
460 padding-right: 0.64em;
461 color: gray;
462 background: linear-gradient(to right, rgb(255, 255, 255) 75%, rgba(255, 255, 255, 0));
463 content: "\25C0";
464 cursor: pointer;
465 }
466
467 .tabbed-labels.tabbed-scroll-right::after {
468 display: inline-block;
469 font-size: 0.9em;
470 position: absolute;
471 top: 0.75em;
472 right: 0;
473 padding-left: 0.64em;
474 color: gray;
475 background: linear-gradient(to right, rgba(255, 255, 255, 0), rgb(255, 255, 255) 25%);
476 content: "\25B6";
477 cursor: pointer;
478 }
479
480 .tabbed-alternate .tabbed-content {
481 width: 100%;
482 }
483 .tabbed-alternate input:nth-child(1):checked ~ .tabbed-content > :nth-child(1),
484 .tabbed-alternate input:nth-child(2):checked ~ .tabbed-content > :nth-child(2),
485 .tabbed-alternate input:nth-child(3):checked ~ .tabbed-content > :nth-child(3) {
486 display: block;
487 }
488 .tabbed-alternate .tabbed-block {
489 display: none;
490 }
491 @media screen {
492 .tabbed-alternate input:nth-child(1):checked ~ .tabbed-labels > :nth-child(1),
493 .tabbed-alternate input:nth-child(2):checked ~ .tabbed-labels > :nth-child(2),
494 .tabbed-alternate input:nth-child(3):checked ~ .tabbed-labels > :nth-child(3) {
495 color: red;
496 border-color: red;
497 }
498 }
499 @media print {
500 .tabbed-labels {
501 display: contents;
502 }
503 .tabbed-labels > label:nth-child(1) {
504 order: 1;
505 }
506 .tabbed-labels > label:nth-child(2) {
507 order: 2;
508 }
509 .tabbed-labels > label:nth-child(3) {
510 order: 3;
511 }
512
513 .tabbed-alternate .tabbed-content {
514 display: contents;
515 }
516 .tabbed-alternate .tabbed-block {
517 display: block;
518 }
519 .tabbed-alternate .tabbed-block:nth-child(1) {
520 order: 1;
521 }
522 .tabbed-alternate .tabbed-block:nth-child(2) {
523 order: 2;
524 }
525 .tabbed-alternate .tabbed-block:nth-child(3) {
526 order: 3;
527 }
528 }
529 ```
530 ////
531
532 === "JS"
533 //// collapse-code
534 ```js
535 // Identify whether a tab bar can be scrolled left or right and apply indicator classes
536 const tabOverflow = () => {
537 const checkScroll = e => {
538 // Use a margin as we just don't always align exactly on the right.
539 const margin = 3
540 const target = e.target
541 if (!e.target.matches('.tabbed-labels')) {
542 return
543 }
544
545 const scrollWidth = target.scrollWidth - target.clientWidth
546 target.classList.remove('tabbed-scroll-left', 'tabbed-scroll-right')
547 if (e.type === "resize" || e.type === "scroll") {
548 if (scrollWidth === 0) {
549 return
550 }
551 if (!target.scrollLeft) {
552 target.classList.add('tabbed-scroll-right')
553 } else if (target.scrollLeft < scrollWidth - margin){
554 target.classList.add('tabbed-scroll-left', 'tabbed-scroll-right')
555 } else {
556 target.classList.add('tabbed-scroll-left')
557 }
558 }
559 }
560
561 // Change the tab to either the previous or next input - depending on which indicator was clicked.
562 // Make sure the current, selected input is scrolled into view.
563 const tabChange = e => {
564 const target = e.target
565 const selected = target.closest('.tabbed-set').querySelector('input:checked')
566 let updated = null
567
568 if (target.classList.contains('tabbed-scroll-right') && e.offsetX >= e.target.offsetWidth - 15) {
569 const sib = selected.nextSibling
570 updated = selected
571 if (sib && sib.tagName === 'INPUT') {
572 updated = sib
573 }
574 } else if (target.classList.contains('tabbed-scroll-left') && e.offsetX <= 15) {
575 const sib = selected.previousSibling
576 updated = selected
577 if (sib && sib.tagName === 'INPUT') {
578 updated = sib
579 }
580 }
581 if (updated) {
582 updated.click()
583 }
584 }
585
586 const onResize = new ResizeObserver(entries => {
587 entries.forEach(entry => {
588 checkScroll({target: entry.target, type: 'resize'})
589 })
590 })
591
592 const labels = document.querySelectorAll('.tabbed-alternate > .tabbed-labels')
593 labels.forEach(el => {
594 checkScroll({target: el, type: 'resize'})
595 onResize.observe(el)
596 el.addEventListener('resize', checkScroll)
597 el.addEventListener('scroll', checkScroll)
598 el.addEventListener('click', tabChange)
599 })
600 }
601
602 // Smooth scroll tab into view when changed
603 const tabScroll = () => {
604 const tabs = document.querySelectorAll(".tabbed-alternate > input")
605 for (const tab of tabs) {
606 tab.addEventListener("change", () => {
607 const label = document.querySelector(`label[for=${tab.id}]`)
608 label.scrollIntoView({block: "nearest", inline: "nearest", behavior: "smooth"})
609 })
610 }
611 }
612
613 // Should run after document loaded, but for illustration purposes:
614 tabOverflow()
615 tabScroll()
616 ```
617 ////
618 ///
619
620 ## Options
621
622 Option | Type | Default | Description
623 --------------------- | -------- | ------------- | -----------
624 `alternate_style` | bool | `#!py3 False` | Use the experimental, alternative style.
625 `slugify` | function | `#!py3 None` | A function to generate slugs from tab titles.
626 `separator` | string | `#!py3 '-'` | Default word separator when generating slugs.
627 `combine_header_slug` | bool | Combine the parent header slug with the tab content slug.