MkDocs Cheatsheet¶
MkDocs - Project Documentation with Markdown
MkDocs is a fast, simple and downright gorgeous static site generator that's geared towards building project documentation. Documentation source files are written in Markdown, and configured with a single YAML configuration file.
Table of Contents¶
- Installation
- Getting Started
- Project Structure
- Configuration
- Writing Documentation
- Navigation
- Themes
- Plugins
- Extensions
- Deployment
- Custom Themes
- Advanced Configuration
- Internationalization
- Search
- API Documentation
- Performance
- Best Practices
Installation¶
Python Installation¶
# Install Python (if not already installed)
# MkDocs requires Python 3.7+
# Check Python version
python --version
python3 --version
Install MkDocs¶
# Install via pip
pip install mkdocs
# Install with additional dependencies
pip install mkdocs[i18n]
# Install specific version
pip install mkdocs==1.5.3
# Verify installation
mkdocs --version
Virtual Environment (Recommended)¶
# Create virtual environment
python -m venv mkdocs-env
# Activate virtual environment
# On Windows
mkdocs-env\Scripts\activate
# On macOS/Linux
source mkdocs-env/bin/activate
# Install MkDocs
pip install mkdocs
# Deactivate when done
deactivate
Development Installation¶
# Install from source
git clone https://github.com/mkdocs/mkdocs.git
cd mkdocs
pip install -e .
# Install development dependencies
pip install -r requirements/dev.txt
Getting Started¶
Create New Project¶
# Create new MkDocs project
mkdocs new my-project
# Navigate to project directory
cd my-project
# Project structure created:
# my-project/
# ├── docs/
# │ └── index.md
# └── mkdocs.yml
Basic Commands¶
# Start development server
mkdocs serve
# Start on custom port
mkdocs serve --dev-addr=127.0.0.1:8080
# Build static site
mkdocs build
# Build and clean output directory
mkdocs build --clean
# Deploy to GitHub Pages
mkdocs gh-deploy
First Documentation¶
<!-- docs/index.md -->
# Welcome to My Project
This is the homepage of my documentation.
## Features
- Easy to use
- Fast and responsive
- Beautiful themes
## Getting Started
Check out the [User Guide](user-guide.md) to get started.
# mkdocs.yml
site_name: My Project Documentation
site_description: A comprehensive guide to my project
site_author: Your Name
site_url: https://yourname.github.io/my-project
nav:
- Home: index.md
- User Guide: user-guide.md
- API Reference: api.md
theme:
name: material
Project Structure¶
Basic Structure¶
my-project/
├── docs/ # Documentation source files
│ ├── index.md # Homepage
│ ├── user-guide.md # User guide
│ ├── api.md # API documentation
│ ├── images/ # Images and assets
│ └── stylesheets/ # Custom CSS
├── mkdocs.yml # Configuration file
└── site/ # Generated site (after build)
Advanced Structure¶
my-project/
├── docs/
│ ├── index.md
│ ├── getting-started/
│ │ ├── index.md
│ │ ├── installation.md
│ │ └── quickstart.md
│ ├── user-guide/
│ │ ├── index.md
│ │ ├── configuration.md
│ │ └── advanced.md
│ ├── api/
│ │ ├── index.md
│ │ ├── endpoints.md
│ │ └── examples.md
│ ├── assets/
│ │ ├── images/
│ │ ├── css/
│ │ └── js/
│ └── overrides/ # Theme overrides
├── mkdocs.yml
├── requirements.txt # Python dependencies
└── .github/
└── workflows/
└── ci.yml # GitHub Actions
Multi-language Structure¶
my-project/
├── docs/
│ ├── en/ # English documentation
│ │ ├── index.md
│ │ └── guide.md
│ ├── es/ # Spanish documentation
│ │ ├── index.md
│ │ └── guide.md
│ └── fr/ # French documentation
│ ├── index.md
│ └── guide.md
├── mkdocs.yml
├── mkdocs.es.yml # Spanish config
└── mkdocs.fr.yml # French config
Configuration¶
Basic Configuration¶
# mkdocs.yml
site_name: My Project
site_description: A great project
site_author: Your Name
site_url: https://example.com
# Repository
repo_name: username/repository
repo_url: https://github.com/username/repository
edit_uri: edit/main/docs/
# Copyright
copyright: Copyright © 2023 Your Name
# Navigation
nav:
- Home: index.md
- Getting Started:
- Installation: getting-started/installation.md
- Quick Start: getting-started/quickstart.md
- User Guide:
- Overview: user-guide/index.md
- Configuration: user-guide/configuration.md
- API Reference: api.md
# Theme
theme:
name: material
language: en
# Build
docs_dir: docs
site_dir: site
Advanced Configuration¶
# mkdocs.yml
site_name: Advanced Project Documentation
site_description: Comprehensive documentation with advanced features
site_author: Your Name
site_url: https://docs.example.com
# Repository information
repo_name: username/project
repo_url: https://github.com/username/project
edit_uri: edit/main/docs/
# Copyright and legal
copyright: |
Copyright © 2023 <a href="https://example.com">Your Company</a><br>
Licensed under <a href="https://opensource.org/licenses/MIT">MIT License</a>
# Navigation structure
nav:
- Home: index.md
- Getting Started:
- Overview: getting-started/index.md
- Installation: getting-started/installation.md
- Quick Start: getting-started/quickstart.md
- Configuration: getting-started/configuration.md
- User Guide:
- Introduction: user-guide/index.md
- Basic Usage: user-guide/basic-usage.md
- Advanced Features: user-guide/advanced.md
- Troubleshooting: user-guide/troubleshooting.md
- API Reference:
- Overview: api/index.md
- Authentication: api/auth.md
- Endpoints: api/endpoints.md
- Examples: api/examples.md
- Development:
- Contributing: development/contributing.md
- Testing: development/testing.md
- Release Notes: development/changelog.md
# Theme configuration
theme:
name: material
language: en
palette:
- scheme: default
primary: indigo
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
- scheme: slate
primary: indigo
accent: indigo
toggle:
icon: material/brightness-4
name: Switch to light mode
font:
text: Roboto
code: Roboto Mono
features:
- navigation.tabs
- navigation.sections
- navigation.expand
- navigation.top
- search.highlight
- search.share
- content.code.copy
# Plugins
plugins:
- search:
lang: en
- minify:
minify_html: true
- git-revision-date-localized:
type: date
# Markdown extensions
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.inlinehilite
- pymdownx.snippets
- pymdownx.tabbed:
alternate_style: true
- attr_list
- md_in_html
- tables
- footnotes
- toc:
permalink: true
# Extra CSS and JavaScript
extra_css:
- stylesheets/extra.css
- stylesheets/custom.css
extra_javascript:
- javascripts/extra.js
- https://unpkg.com/mermaid@8.6.4/dist/mermaid.min.js
# Extra configuration
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/username
- icon: fontawesome/brands/twitter
link: https://twitter.com/username
- icon: fontawesome/brands/linkedin
link: https://linkedin.com/in/username
analytics:
provider: google
property: G-XXXXXXXXXX
version:
provider: mike
Environment-specific Configuration¶
# mkdocs.yml (base configuration)
site_name: My Project
docs_dir: docs
site_dir: site
# Development configuration
dev_addr: 127.0.0.1:8000
use_directory_urls: true
# Production configuration
site_url: https://docs.example.com
use_directory_urls: false
Writing Documentation¶
Markdown Basics¶
# Heading 1
## Heading 2
### Heading 3
**Bold text**
*Italic text*
~~Strikethrough~~
`Inline code`
- Unordered list item 1
- Unordered list item 2
- Nested item
1. Ordered list item 1
2. Ordered list item 2
[Link text](https://example.com)
[Internal link](user-guide.md)
[Link with title](https://example.com "Title")


Code Blocks¶
```python
def hello_world():
print("Hello, World!")
```
```python title="example.py"
def greet(name):
return f"Hello, {name}!"
print(greet("MkDocs"))
```
```python linenums="1"
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
```
```python hl_lines="2 3"
def process_data(data):
cleaned_data = clean(data) # This line is highlighted
result = analyze(cleaned_data) # This line is highlighted
return result
```
Tables¶
| Feature | Description | Status |
|---------|-------------|--------|
| Search | Full-text search | ✅ Complete |
| Themes | Multiple themes | ✅ Complete |
| Plugins | Extensible | 🚧 In Progress |
| Left Aligned | Center Aligned | Right Aligned |
|:-------------|:--------------:|--------------:|
| Left | Center | Right |
| Text | Text | Text |
Admonitions¶
!!! note
This is a note admonition.
!!! tip "Custom Title"
This is a tip with a custom title.
!!! warning
This is a warning admonition.
!!! danger "Critical"
This is a danger admonition with custom title.
!!! info "Information"
This is an info admonition.
!!! success
This is a success admonition.
!!! failure
This is a failure admonition.
!!! question "FAQ"
This is a question admonition.
??? note "Collapsible Note"
This note is collapsible.
???+ tip "Expanded by Default"
This tip is expanded by default.
Content Tabs¶
=== "Python"
```python
def hello():
print("Hello from Python!")
```
=== "JavaScript"
```javascript
function hello() {
console.log("Hello from JavaScript!");
}
```
=== "Bash"
```bash
echo "Hello from Bash!"
```
Footnotes¶
This is a sentence with a footnote[^1].
Another sentence with a footnote[^note].
[^1]: This is the first footnote.
[^note]: This is a named footnote.
Navigation¶
Simple Navigation¶
Hierarchical Navigation¶
nav:
- Home: index.md
- Getting Started:
- Installation: getting-started/installation.md
- Quick Start: getting-started/quickstart.md
- Configuration: getting-started/configuration.md
- User Guide:
- Overview: user-guide/index.md
- Basic Usage: user-guide/basic.md
- Advanced Usage: user-guide/advanced.md
- API Reference:
- Overview: api/index.md
- Authentication: api/auth.md
- Endpoints:
- Users: api/endpoints/users.md
- Posts: api/endpoints/posts.md
- Comments: api/endpoints/comments.md
Auto-generated Navigation¶
# Automatic navigation based on file structure
# Remove nav section to enable auto-generation
plugins:
- awesome-pages:
filename: .pages
collapse_single_pages: true
strict: false
Navigation with External Links¶
nav:
- Home: index.md
- Documentation:
- User Guide: user-guide.md
- API Reference: api.md
- External Links:
- GitHub: https://github.com/username/project
- Issues: https://github.com/username/project/issues
- Discussions: https://github.com/username/project/discussions
Themes¶
Material Theme¶
# mkdocs.yml
theme:
name: material
palette:
# Palette toggle for light mode
- scheme: default
primary: indigo
accent: indigo
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- scheme: slate
primary: indigo
accent: indigo
toggle:
icon: material/brightness-4
name: Switch to light mode
font:
text: Roboto
code: Roboto Mono
features:
- navigation.tabs
- navigation.sections
- navigation.expand
- navigation.top
- search.highlight
- search.share
- content.code.copy
- content.code.annotate
icon:
repo: fontawesome/brands/github
ReadTheDocs Theme¶
Custom Theme Configuration¶
theme:
name: material
custom_dir: overrides
palette:
primary: teal
accent: orange
font:
text: Ubuntu
code: Ubuntu Mono
logo: assets/logo.png
favicon: assets/favicon.ico
features:
- navigation.instant
- navigation.tracking
- navigation.tabs
- navigation.tabs.sticky
- navigation.sections
- navigation.expand
- navigation.indexes
- navigation.top
- search.highlight
- search.share
- search.suggest
- header.autohide
- content.code.copy
- content.code.annotate
Theme Switching¶
theme:
name: material
palette:
- media: "(prefers-color-scheme: light)"
scheme: default
primary: blue
toggle:
icon: material/brightness-7
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: blue
toggle:
icon: material/brightness-4
name: Switch to light mode
Plugins¶
Essential Plugins¶
# Install common plugins
pip install mkdocs-material
pip install mkdocs-minify-plugin
pip install mkdocs-git-revision-date-localized-plugin
pip install mkdocs-awesome-pages-plugin
pip install mkdocs-redirects
Search Plugin¶
plugins:
- search:
lang:
- en
- es
separator: '[\s\-,:!=\[\]()"/]+|(?!\b)(?=[A-Z][a-z])|\.(?!\d)|&[lg]t;'
prebuild_index: true
Git Revision Date Plugin¶
plugins:
- git-revision-date-localized:
type: date
timezone: UTC
locale: en
fallback_to_build_date: false
enable_creation_date: true
Minify Plugin¶
plugins:
- minify:
minify_html: true
minify_js: true
minify_css: true
htmlmin_opts:
remove_comments: true
cache_safe: true
Awesome Pages Plugin¶
Redirects Plugin¶
plugins:
- redirects:
redirect_maps:
'old-page.md': 'new-page.md'
'old-section/index.md': 'new-section/index.md'
'legacy/': 'current/'
Custom Plugin Configuration¶
plugins:
- search
- minify:
minify_html: true
- git-revision-date-localized:
type: datetime
timezone: America/New_York
- awesome-pages
- redirects:
redirect_maps:
'changelog.md': 'development/changelog.md'
- macros:
module_name: docs/macros
- mkdocstrings:
handlers:
python:
options:
docstring_style: google
Extensions¶
PyMdown Extensions¶
markdown_extensions:
# Python Markdown
- abbr
- admonition
- attr_list
- def_list
- footnotes
- md_in_html
- toc:
permalink: true
title: On this page
- tables
# PyMdown Extensions
- pymdownx.arithmatex:
generic: true
- pymdownx.betterem:
smart_enable: all
- pymdownx.caret
- pymdownx.details
- pymdownx.emoji:
emoji_generator: !!python/name:materialx.emoji.to_svg
emoji_index: !!python/name:materialx.emoji.twemoji
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
- pymdownx.inlinehilite
- pymdownx.keys
- pymdownx.magiclink:
repo_url_shorthand: true
user: username
repo: repository
- pymdownx.mark
- pymdownx.smartsymbols
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
- pymdownx.tabbed:
alternate_style: true
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.tilde
Code Highlighting¶
markdown_extensions:
- pymdownx.highlight:
anchor_linenums: true
line_spans: __span
pygments_lang_class: true
auto_title: true
linenums: true
- pymdownx.inlinehilite
- pymdownx.snippets:
base_path: docs
check_paths: true
- pymdownx.superfences:
custom_fences:
- name: mermaid
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
Math Support¶
markdown_extensions:
- pymdownx.arithmatex:
generic: true
extra_javascript:
- javascripts/mathjax.js
- https://polyfill.io/v3/polyfill.min.js?features=es6
- https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
// docs/javascripts/mathjax.js
window.MathJax = {
tex: {
inlineMath: [["\\(", "\\)"]],
displayMath: [["\\[", "\\]"]],
processEscapes: true,
processEnvironments: true
},
options: {
ignoreHtmlClass: ".*|",
processHtmlClass: "arithmatex"
}
};
document$.subscribe(() => {
MathJax.typesetPromise()
})
Deployment¶
GitHub Pages¶
# Deploy to GitHub Pages
mkdocs gh-deploy
# Deploy with custom commit message
mkdocs gh-deploy --message "Deploy documentation updates"
# Deploy to custom branch
mkdocs gh-deploy --remote-branch gh-pages
GitHub Actions¶
# .github/workflows/ci.yml
name: ci
on:
push:
branches:
- master
- main
permissions:
contents: write
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: 3.x
- run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
- uses: actions/cache@v3
with:
key: mkdocs-material-${{ env.cache_id }}
path: .cache
restore-keys: |
mkdocs-material-
- run: pip install mkdocs-material
- run: mkdocs gh-deploy --force
Netlify¶
# netlify.toml
[build]
publish = "site"
command = "mkdocs build"
[build.environment]
PYTHON_VERSION = "3.8"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
Vercel¶
{
"builds": [
{
"src": "mkdocs.yml",
"use": "@vercel/python"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/site/$1"
}
]
}
Docker Deployment¶
# Dockerfile
FROM python:3.9-slim
WORKDIR /docs
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["mkdocs", "serve", "--dev-addr=0.0.0.0:8000"]
# docker-compose.yml
version: '3.8'
services:
mkdocs:
build: .
ports:
- "8000:8000"
volumes:
- .:/docs
environment:
- PYTHONUNBUFFERED=1
Custom Domain¶
# mkdocs.yml
site_url: https://docs.example.com
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/username/project
Custom Themes¶
Theme Structure¶
custom_theme/
├── 404.html
├── base.html
├── content.html
├── nav.html
├── nav-sub.html
├── search.html
├── toc.html
├── css/
│ ├── base.css
│ └── bootstrap.min.css
├── js/
│ ├── base.js
│ └── bootstrap.min.js
└── img/
└── favicon.ico
Base Template¶
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% if page_description %}
<meta name="description" content="{{ page_description }}">
{% endif %}
{% if site_author %}
<meta name="author" content="{{ site_author }}">
{% endif %}
{% if canonical_url %}
<link rel="canonical" href="{{ canonical_url }}">
{% endif %}
<link rel="shortcut icon" href="{{ 'img/favicon.ico'|url }}">
<title>{% if page_title %}{{ page_title }} - {% endif %}{{ site_name }}</title>
<link href="{{ 'css/bootstrap.min.css'|url }}" rel="stylesheet">
<link href="{{ 'css/base.css'|url }}" rel="stylesheet">
{% for path in config['extra_css'] %}
<link href="{{ path|url }}" rel="stylesheet">
{% endfor %}
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Navigation content -->
{% include "nav.html" %}
</div>
</div>
<div class="container">
<div class="row">
{% if nav %}
<div class="col-md-3">
{% include "toc.html" %}
</div>
<div class="col-md-9" role="main">
{% else %}
<div class="col-md-12" role="main">
{% endif %}
{% include "content.html" %}
</div>
</div>
</div>
<script src="{{ 'js/jquery.min.js'|url }}"></script>
<script src="{{ 'js/bootstrap.min.js'|url }}"></script>
<script src="{{ 'js/base.js'|url }}"></script>
{% for path in config['extra_javascript'] %}
<script src="{{ path|url }}"></script>
{% endfor %}
</body>
</html>
Content Template¶
<!-- content.html -->
{% if meta.source %}
<div class="source-links">
{% for filename in meta.source %}
<span class="label label-primary">{{ filename }}</span>
{% endfor %}
</div>
{% endif %}
{{ page.content }}
{% if page and page.edit_url %}
<div class="edit-page">
<a href="{{ page.edit_url }}" class="btn btn-default">
<i class="fa fa-edit"></i> Edit this page
</a>
</div>
{% endif %}
{% if page and page.next_page %}
<div class="pagination">
<a href="{{ page.next_page.url|url }}" class="btn btn-primary">
Next: {{ page.next_page.title }}
</a>
</div>
{% endif %}
Navigation Template¶
<!-- nav.html -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{ nav.homepage.url|url }}">{{ site_name }}</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
{% for nav_item in nav %}
{% if nav_item.children %}
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
{{ nav_item.title }} <b class="caret"></b>
</a>
<ul class="dropdown-menu">
{% for nav_item in nav_item.children %}
<li>
<a href="{{ nav_item.url|url }}">{{ nav_item.title }}</a>
</li>
{% endfor %}
</ul>
</li>
{% else %}
<li {% if nav_item.active %}class="active"{% endif %}>
<a href="{{ nav_item.url|url }}">{{ nav_item.title }}</a>
</li>
{% endif %}
{% endfor %}
</ul>
{% if config.repo_url %}
<ul class="nav navbar-nav navbar-right">
<li>
<a href="{{ config.repo_url }}" class="navbar-link">
<i class="fa fa-github"></i> GitHub
</a>
</li>
</ul>
{% endif %}
</div>
Advanced Configuration¶
Multi-site Configuration¶
# mkdocs.yml (main site)
site_name: Main Documentation
site_url: https://docs.example.com
nav:
- Home: index.md
- API: api/
- Guides: guides/
plugins:
- multirepo:
cleanup: true
keep_docs_dir: true
repos:
- name: api-docs
import_url: https://github.com/username/api-docs
imports: [
docs/api.md,
docs/endpoints/
]
Environment Variables¶
# mkdocs.yml
site_name: !ENV [SITE_NAME, 'Default Site Name']
site_url: !ENV SITE_URL
extra:
version: !ENV VERSION
api_url: !ENV [API_URL, 'https://api.example.com']
Conditional Configuration¶
# mkdocs.yml
site_name: My Documentation
# Development configuration
dev_addr: !ENV [DEV_ADDR, '127.0.0.1:8000']
# Production configuration
site_url: !ENV SITE_URL
plugins:
- search
- !ENV [ANALYTICS_PLUGIN, 'null']
extra:
analytics: !ENV [ANALYTICS_CONFIG, {}]
Custom Hooks¶
# hooks.py
import os
from mkdocs.plugins import BasePlugin
class CustomHook(BasePlugin):
def on_pre_build(self, config):
"""Run before the build starts"""
print("Starting build...")
def on_post_build(self, config):
"""Run after the build completes"""
print("Build completed!")
def on_page_markdown(self, markdown, page, config, files):
"""Process page markdown"""
# Add custom processing
return markdown
def on_page_content(self, html, page, config, files):
"""Process page HTML content"""
# Add custom processing
return html
Internationalization¶
Multi-language Setup¶
# mkdocs.yml
plugins:
- i18n:
default_language: en
languages:
en:
name: English
build: true
es:
name: Español
build: true
fr:
name: Français
build: true
nav_translations:
es:
Home: Inicio
Getting Started: Comenzando
User Guide: Guía del Usuario
fr:
Home: Accueil
Getting Started: Commencer
User Guide: Guide Utilisateur
Language-specific Content¶
<!-- docs/index.md -->
# Welcome
{% if config.theme.language == 'es' %}
¡Bienvenido a nuestra documentación!
{% elif config.theme.language == 'fr' %}
Bienvenue dans notre documentation!
{% else %}
Welcome to our documentation!
{% endif %}
Translation Structure¶
docs/
├── en/
│ ├── index.md
│ ├── getting-started.md
│ └── user-guide.md
├── es/
│ ├── index.md
│ ├── comenzando.md
│ └── guia-usuario.md
└── fr/
├── index.md
├── commencer.md
└── guide-utilisateur.md
Search¶
Local Search Configuration¶
plugins:
- search:
lang:
- en
- es
- fr
separator: '[\s\-,:!=\[\]()"/]+|(?!\b)(?=[A-Z][a-z])|\.(?!\d)|&[lg]t;'
min_search_length: 2
prebuild_index: python
indexing: 'full'
External Search Integration¶
# Algolia DocSearch
extra_javascript:
- https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js
- javascripts/search.js
extra_css:
- https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.css
// docs/javascripts/search.js
docsearch({
apiKey: 'your-api-key',
indexName: 'your-index-name',
inputSelector: '#search-input',
debug: false
});
Custom Search¶
<!-- overrides/partials/search.html -->
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query"
placeholder="Search documentation" autocapitalize="off"
autocorrect="off" autocomplete="off" spellcheck="false"
data-md-component="search-query">
<label class="md-search__icon md-icon" for="__search">
<svg viewBox="0 0 24 24"><path d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z"></path></svg>
</label>
<nav class="md-search__options" aria-label="Search">
<button type="reset" class="md-search__icon md-icon" tabindex="-1">
<svg viewBox="0 0 24 24"><path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z"></path></svg>
</button>
</nav>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="search-result">
<div class="md-search-result__meta">
Initializing search
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
API Documentation¶
Auto-generated API Docs¶
# mkdocs.yml
plugins:
- mkdocstrings:
handlers:
python:
options:
docstring_style: google
show_source: true
show_root_heading: true
show_root_toc_entry: true
show_object_full_path: false
show_category_heading: true
group_by_category: true
heading_level: 2
<!-- docs/api.md -->
# API Reference
## Core Module
::: myproject.core
options:
show_source: false
heading_level: 3
## Utilities
::: myproject.utils
options:
members:
- helper_function
- UtilityClass
OpenAPI Integration¶
Manual API Documentation¶
# API Reference
## Authentication
All API requests require authentication using an API key.
```http
GET /api/v1/users
Authorization: Bearer YOUR_API_KEY
Endpoints¶
GET /api/v1/users¶
Retrieve a list of users.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
limit |
integer | No | Maximum number of users to return (default: 10) |
offset |
integer | No | Number of users to skip (default: 0) |
Response:
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
],
"total": 100,
"limit": 10,
"offset": 0
}
Example:
## Performance
### Build Optimization
```yaml
# mkdocs.yml
plugins:
- search:
prebuild_index: python
- minify:
minify_html: true
minify_js: true
minify_css: true
cache_safe: true
- optimize:
enabled: !ENV [OPTIMIZE, false]
print_page_size: true
print_pure_css_size: true
print_js_size: true
extra:
generator: false # Remove "Made with Material for MkDocs"
Caching Strategy¶
# mkdocs.yml
plugins:
- search:
prebuild_index: true
- git-revision-date-localized:
enable_creation_date: true
fallback_to_build_date: false
extra:
version:
provider: mike
default: latest
Image Optimization¶
# Install image optimization tools
pip install mkdocs-img2fig-plugin
pip install mkdocs-optimize-plugin
# mkdocs.yml
plugins:
- img2fig
- optimize:
enabled: !ENV [OPTIMIZE, false]
optimize_png: true
optimize_jpg: true
optimize_svg: true
Lazy Loading¶
<!-- Custom image component -->
<img src="{{ image_url }}"
alt="{{ alt_text }}"
loading="lazy"
decoding="async">
Best Practices¶
Content Organization¶
# Recommended structure
docs/
├── index.md # Homepage
├── getting-started/ # Getting started guide
│ ├── index.md
│ ├── installation.md
│ └── quickstart.md
├── user-guide/ # Detailed user guide
│ ├── index.md
│ ├── basic-usage.md
│ └── advanced-features.md
├── api/ # API documentation
│ ├── index.md
│ ├── authentication.md
│ └── endpoints.md
├── development/ # Development docs
│ ├── contributing.md
│ ├── testing.md
│ └── changelog.md
├── assets/ # Images and files
│ ├── images/
│ ├── css/
│ └── js/
└── overrides/ # Theme customizations
Writing Best Practices¶
- Use clear headings for better navigation
- Include code examples with proper syntax highlighting
- Add screenshots for visual guidance
- Write concise descriptions for better understanding
- Use consistent formatting across all pages
- Include cross-references between related topics
SEO Optimization¶
# mkdocs.yml
site_name: Your Project Documentation
site_description: Comprehensive documentation for Your Project
site_author: Your Name
site_url: https://docs.yourproject.com
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/username/project
- icon: fontawesome/brands/twitter
link: https://twitter.com/username
plugins:
- meta
- sitemap:
change_frequency: daily
priority: 1.0
Maintenance Best Practices¶
- Regular updates to keep content current
- Link checking to prevent broken links
- Performance monitoring for build times
- User feedback integration for improvements
- Version control for documentation changes
- Automated testing for documentation builds
Summary¶
MkDocs is a powerful static site generator specifically designed for project documentation. Key features include:
- Markdown-based: Write documentation in simple Markdown
- Python-powered: Extensible with Python plugins
- Theme support: Beautiful themes including Material Design
- Live preview: Real-time preview during development
- Easy deployment: Simple deployment to various platforms
- Plugin ecosystem: Rich ecosystem of plugins for extended functionality
- Search integration: Built-in search with external search support
- Multi-language: Support for internationalization
By following best practices and leveraging MkDocs' capabilities, you can create professional, maintainable documentation that serves your users effectively and grows with your project.