Read the Docs with MkDocs Guide

Table of Contents


Introduction

What is MkDocs?

MkDocs is a fast, simple static site generator for building project documentation.

Key Features: - ✅ Write docs in Markdown - ✅ Beautiful, responsive themes - ✅ Live preview server - ✅ Easy to customize - ✅ Plugin ecosystem - ✅ SEO friendly

What is Read the Docs?

Read the Docs is a documentation hosting platform that builds, versions, and hosts your docs.

Key Features: - ✅ Free hosting for open source - ✅ Automatic builds from Git - ✅ Version management - ✅ Search functionality - ✅ PDF/ePub generation - ✅ Analytics

Why Use MkDocs with Read the Docs?

Perfect combination: - MkDocs creates beautiful docs - Read the Docs hosts and manages them - Automatic deployment on Git push - Professional documentation workflow


Installation and Setup

Prerequisites

# Python 3.7 or higher
python --version

# pip (usually comes with Python)
pip --version

Install MkDocs

# Install MkDocs
pip install mkdocs

# Verify installation
mkdocs --version

# Install Material theme (recommended)
pip install mkdocs-material

Create New Project

# Create new MkDocs project
mkdocs new my-project

# Navigate to project
cd my-project

# View project structure
ls -la

Created structure:

my-project/
├── docs/
│   └── index.md
└── mkdocs.yml

Start Development Server

# Start local server
mkdocs serve

# Access at: http://127.0.0.1:8000
# Auto-reloads on file changes

Custom host/port:

# Custom host and port
mkdocs serve --dev-addr=0.0.0.0:8080

# Strict mode (warnings become errors)
mkdocs serve --strict

MkDocs Basics

Basic Commands

# Create new project
mkdocs new [project-name]

# Start development server
mkdocs serve

# Build static site
mkdocs build

# Build and serve
mkdocs build --clean

# Deploy to GitHub Pages
mkdocs gh-deploy

# Get help
mkdocs --help

Building Documentation

# Build documentation
mkdocs build

# Output directory: site/
# Contents:
# - HTML files
# - CSS/JS assets
# - Search index

Clean build:

# Remove old files before building
mkdocs build --clean

# Strict mode (fail on warnings)
mkdocs build --strict

Project Structure

Basic Structure

my-project/
├── docs/
│   ├── index.md              # Homepage
│   ├── getting-started.md
│   ├── user-guide/
│   │   ├── installation.md
│   │   └── configuration.md
│   ├── api-reference/
│   │   └── modules.md
│   └── assets/
│       ├── images/
│       └── css/
├── mkdocs.yml               # Configuration file
├── requirements.txt         # Python dependencies
└── .readthedocs.yaml       # Read the Docs config
project-docs/
├── docs/
│   ├── index.md                    # Home
│   ├── getting-started/
│   │   ├── index.md
│   │   ├── installation.md
│   │   ├── quickstart.md
│   │   └── configuration.md
│   ├── user-guide/
│   │   ├── index.md
│   │   ├── basic-usage.md
│   │   └── advanced-features.md
│   ├── api-reference/
│   │   ├── index.md
│   │   └── modules.md
│   ├── tutorials/
│   │   ├── index.md
│   │   └── tutorial-1.md
│   ├── contributing.md
│   ├── changelog.md
│   └── assets/
│       ├── images/
│       ├── css/
│       │   └── extra.css
│       └── js/
│           └── extra.js
├── mkdocs.yml
├── requirements.txt
└── .readthedocs.yaml

Configuration

Basic mkdocs.yml

# Project information
site_name: My Project Documentation
site_url: https://my-project.readthedocs.io
site_author: Your Name
site_description: A comprehensive documentation for My Project

# Repository
repo_name: username/my-project
repo_url: https://github.com/username/my-project
edit_uri: edit/main/docs/

# Copyright
copyright: Copyright © 2024 Your Name

# Navigation
nav:
  - Home: index.md
  - Getting Started:
      - Installation: getting-started/installation.md
      - Quick Start: getting-started/quickstart.md
  - User Guide:
      - Basic Usage: user-guide/basic-usage.md
      - Advanced: user-guide/advanced.md
  - API Reference: api-reference/index.md
  - Contributing: contributing.md

# Theme
theme:
  name: material

# Extensions
markdown_extensions:
  - admonition
  - codehilite
  - toc:
      permalink: true

Advanced Configuration

site_name: My Project Documentation
site_url: https://my-project.readthedocs.io
site_author: Your Name
site_description: >-
  A comprehensive documentation for My Project
  with examples, tutorials, and API reference

# Repository
repo_name: username/my-project
repo_url: https://github.com/username/my-project
edit_uri: edit/main/docs/

# Copyright
copyright: |
  Copyright &copy; 2024 <a href="https://github.com/username">Your Name</a>

# 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-usage.md
      - Advanced Features: user-guide/advanced.md
  - Tutorials:
      - Tutorial 1: tutorials/tutorial-1.md
      - Tutorial 2: tutorials/tutorial-2.md
  - API Reference:
      - Overview: api-reference/index.md
      - Modules: api-reference/modules.md
  - Contributing: contributing.md
  - Changelog: changelog.md

# Theme configuration
theme:
  name: material
  language: en
  palette:
    # Light mode
    - scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode
    # 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.suggest
    - search.highlight
    - content.code.copy
    - content.action.edit
  icon:
    repo: fontawesome/brands/github

# Plugins
plugins:
  - search:
      lang: en
  - minify:
      minify_html: true

# Extensions
markdown_extensions:
  # Python Markdown
  - abbr
  - admonition
  - attr_list
  - def_list
  - footnotes
  - md_in_html
  - tables
  - toc:
      permalink: true
      toc_depth: 3

  # Python Markdown Extensions
  - pymdownx.arithmatex:
      generic: true
  - pymdownx.betterem:
      smart_enable: all
  - pymdownx.caret
  - pymdownx.details
  - pymdownx.emoji:
      emoji_index: !!python/name:materialx.emoji.twemoji
      emoji_generator: !!python/name:materialx.emoji.to_svg
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
  - pymdownx.inlinehilite
  - pymdownx.keys
  - 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

# Extra CSS and JavaScript
extra_css:
  - assets/css/extra.css

extra_javascript:
  - assets/js/extra.js
  - https://polyfill.io/v3/polyfill.min.js?features=es6
  - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js

# Extra
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
  version:
    provider: mike

Writing Documentation

Markdown Basics

# Heading 1
## Heading 2
### Heading 3

**Bold text**
*Italic text*
~~Strikethrough~~

[Link text](https://example.com)
![Image alt text](images/image.png)

- Bullet list item 1
- Bullet list item 2

1. Numbered list item 1
2. Numbered list item 2

> Blockquote text

`Inline code`

```python
# Code block
def hello():
    print("Hello, World!")

### Admonitions (Callouts)

```markdown
!!! note
    This is a note admonition.

!!! warning
    This is a warning admonition.

!!! danger
    This is a danger admonition.

!!! success
    This is a success admonition.

!!! info
    This is an info admonition.

!!! tip
    This is a tip admonition.

??? note "Collapsible Note"
    This note is collapsed by default.

???+ note "Expanded Note"
    This note is expanded by default.

Output:

!!! note This is a note admonition.

!!! warning This is a warning admonition.

Code Blocks with Highlighting

```python
def fibonacci(n):
    """Calculate Fibonacci number."""
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))
# Install package
pip install mkdocs-material

# Start server
mkdocs serve
// JavaScript example
function greet(name) {
    console.log(`Hello, ${name}!`);
}

### Code Block with Title

```markdown
```python title="fibonacci.py"
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

### Code Block with Line Numbers

```markdown
```python linenums="1"
def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

### Tables

```markdown
| Column 1 | Column 2 | Column 3 |
|----------|----------|----------|
| Row 1    | Data 1   | Value 1  |
| Row 2    | Data 2   | Value 2  |
| Row 3    | Data 3   | Value 3  |

| Left Align | Center Align | Right Align |
|:-----------|:------------:|------------:|
| Left       | Center       | Right       |
| Text       | Text         | Text        |

Tabs

=== "Python"
    ```python
    print("Hello, World!")
    ```

=== "JavaScript"
    ```javascript
    console.log("Hello, World!");
    ```

=== "Bash"
    ```bash
    echo "Hello, World!"
    ```

Task Lists

- [x] Completed task
- [ ] Incomplete task
- [ ] Another task

Footnotes

This is a sentence with a footnote[^1].

[^1]: This is the footnote content.

Math Equations

Inline math: $E = mc^2$

Block math:
$$
\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
$$

Mermaid Diagrams

```mermaid
graph LR
    A[Start] --> B{Decision}
    B -->|Yes| C[Do Something]
    B -->|No| D[Do Something Else]
    C --> E[End]
    D --> E

### Internal Links

```markdown
# Link to another page
[Installation Guide](getting-started/installation.md)

# Link to section on same page
[Jump to Configuration](#configuration)

# Link to section on another page
[See Installation Steps](getting-started/installation.md#installation-steps)

Themes

Installation:

pip install mkdocs-material

Basic configuration:

theme:
  name: material
  palette:
    primary: indigo
    accent: indigo
  font:
    text: Roboto
    code: Roboto Mono

Color schemes:

theme:
  name: material
  palette:
    # Light mode
    - media: "(prefers-color-scheme: light)"
      scheme: default
      primary: blue
      accent: blue
      toggle:
        icon: material/brightness-7
        name: Switch to dark mode

    # Dark mode
    - media: "(prefers-color-scheme: dark)"
      scheme: slate
      primary: blue
      accent: blue
      toggle:
        icon: material/brightness-4
        name: Switch to light mode

Available colors: - red, pink, purple, deep purple - indigo, blue, light blue, cyan - teal, green, light green, lime - yellow, amber, orange, deep orange

Features:

theme:
  name: material
  features:
    # Navigation
    - navigation.instant      # Instant loading
    - navigation.tracking     # Anchor tracking
    - navigation.tabs         # Top-level tabs
    - navigation.sections     # Section index pages
    - navigation.expand       # Expand all sections
    - navigation.indexes      # Section index pages
    - navigation.top          # Back to top button

    # Table of contents
    - toc.follow              # Follow anchor
    - toc.integrate           # Integrate into nav

    # Search
    - search.suggest          # Search suggestions
    - search.highlight        # Highlight search terms
    - search.share            # Share search link

    # Header
    - header.autohide         # Auto-hide header

    # Content
    - content.code.copy       # Copy code button
    - content.code.annotate   # Code annotations
    - content.action.edit     # Edit this page
    - content.action.view     # View source

ReadTheDocs Theme

Installation:

pip install mkdocs-readthedocs

Configuration:

theme:
  name: readthedocs
  highlightjs: true
  hljs_languages:
    - python
    - javascript

Other Themes

# Cinder theme
pip install mkdocs-cinder

# Bootstrap theme
pip install mkdocs-bootstrap

# Windmill theme
pip install mkdocs-windmill

Plugins and Extensions

Essential Plugins

Search Plugin (Built-in)

plugins:
  - search:
      lang: en
      separator: '[\s\-\.]+'

Minify Plugin

pip install mkdocs-minify-plugin
plugins:
  - minify:
      minify_html: true
      minify_js: true
      minify_css: true

PDF Export

pip install mkdocs-pdf-export-plugin
plugins:
  - pdf-export:
      enabled_if_env: ENABLE_PDF_EXPORT

Git Revision Date

pip install mkdocs-git-revision-date-plugin
plugins:
  - git-revision-date

Awesome Pages

pip install mkdocs-awesome-pages-plugin
plugins:
  - awesome-pages

Macros

pip install mkdocs-macros-plugin
plugins:
  - macros

Extension Examples

Code Highlighting

markdown_extensions:
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
  - pymdownx.inlinehilite
  - pymdownx.superfences

Task Lists

markdown_extensions:
  - pymdownx.tasklist:
      custom_checkbox: true

Emoji Support

markdown_extensions:
  - pymdownx.emoji:
      emoji_index: !!python/name:materialx.emoji.twemoji
      emoji_generator: !!python/name:materialx.emoji.to_svg

Read the Docs Integration

Create .readthedocs.yaml

Create file in repository root:

# .readthedocs.yaml
version: 2

# Build configuration
build:
  os: ubuntu-22.04
  tools:
    python: "3.11"
  jobs:
    post_create_environment:
      # Install poetry
      - pip install poetry
    post_install:
      # Install dependencies
      - poetry install --with docs

# Python configuration
python:
  install:
    - requirements: requirements.txt

# MkDocs configuration
mkdocs:
  configuration: mkdocs.yml
  fail_on_warning: false

# Formats
formats:
  - pdf
  - epub

requirements.txt

mkdocs==1.5.3
mkdocs-material==9.4.8
pymdown-extensions==10.3.1
mkdocs-minify-plugin==0.7.1

Setup on Read the Docs

1. Create Account - Go to readthedocs.org - Sign up or sign in with GitHub

2. Import Project - Click "Import a Project" - Select repository from GitHub - Or manually import with Git URL

3. Configure Project - Name: my-project - Repository URL: https://github.com/username/my-project - Default branch: main - Documentation type: mkdocs

4. Build - Click "Build Version" - Wait for build to complete - View documentation at: https://my-project.readthedocs.io

Version Management

Enable versions: 1. Admin → Versions 2. Activate versions you want to build 3. Set default version

Version structure:

https://my-project.readthedocs.io/en/latest/    # Latest
https://my-project.readthedocs.io/en/stable/    # Stable
https://my-project.readthedocs.io/en/v1.0.0/    # Specific version

Webhooks

Automatic builds on push: - Read the Docs automatically creates webhooks - Builds trigger on Git push - Check Admin → Integrations

Manual webhook:

# Trigger build via API
curl -X POST \
  -H "Authorization: Token YOUR_TOKEN" \
  https://readthedocs.org/api/v3/projects/my-project/versions/latest/builds/

Advanced Features

Multi-language Support

# mkdocs.yml
plugins:
  - i18n:
      default_language: en
      languages:
        en: English
        es: Español
        fr: Français
      nav_translations:
        es:
          Home: Inicio
        fr:
          Home: Accueil

Structure:

docs/
├── en/
│   └── index.md
├── es/
│   └── index.md
└── fr/
    └── index.md

API Documentation

Using mkdocstrings:

pip install mkdocstrings[python]
plugins:
  - mkdocstrings:
      handlers:
        python:
          options:
            docstring_style: google
            show_source: true

In markdown:

# API Reference

::: mymodule.myfunction

Search Configuration

plugins:
  - search:
      lang:
        - en
        - es
      separator: '[\s\-\.]+'
      min_search_length: 2
      prebuild_index: true

Custom CSS

docs/assets/css/extra.css:

/* Custom styles */
:root {
  --primary-color: #007bff;
}

.md-header {
  background-color: var(--primary-color);
}

.md-typeset code {
  background-color: #f5f5f5;
}

In mkdocs.yml:

extra_css:
  - assets/css/extra.css

Custom JavaScript

docs/assets/js/extra.js:

// Custom JavaScript
document.addEventListener('DOMContentLoaded', function() {
  console.log('Documentation loaded');
});

In mkdocs.yml:

extra_javascript:
  - assets/js/extra.js

Deployment

GitHub Pages

# Build and deploy to gh-pages branch
mkdocs gh-deploy

# With custom commit message
mkdocs gh-deploy -m "Update documentation"

# Force push
mkdocs gh-deploy --force

Access at: https://username.github.io/repository/

GitLab Pages

.gitlab-ci.yml:

pages:
  stage: deploy
  image: python:3.11
  script:
    - pip install mkdocs-material
    - mkdocs build --site-dir public
  artifacts:
    paths:
      - public
  only:
    - main

Netlify

netlify.toml:

[build]
  command = "mkdocs build"
  publish = "site"

[build.environment]
  PYTHON_VERSION = "3.11"

Custom Server

# Build static site
mkdocs build

# Copy 'site' directory to server
scp -r site/ user@server:/var/www/docs/

# Or use rsync
rsync -avz site/ user@server:/var/www/docs/

Best Practices

Documentation Structure

Good structure:

docs/
├── index.md                      # Homepage
├── getting-started/
│   ├── index.md                  # Overview
│   ├── installation.md
│   ├── quickstart.md
│   └── configuration.md
├── user-guide/
│   ├── index.md
│   ├── basics.md
│   └── advanced.md
├── api-reference/
│   └── index.md
├── tutorials/
│   ├── tutorial-1.md
│   └── tutorial-2.md
├── faq.md
├── contributing.md
└── changelog.md

Writing Tips

1. Clear Headings

# Use H1 for page title only
## H2 for main sections
### H3 for subsections

2. Code Examples - Always include working code examples - Use syntax highlighting - Explain what the code does

3. Screenshots - Use descriptive alt text - Keep images under 500KB - Use PNG for screenshots, JPEG for photos

4. Links - Use relative links for internal pages - Check links regularly - Use descriptive link text

# Good navigation structure
nav:
  - Home: index.md
  - Getting Started:
      - Installation: getting-started/installation.md
      - Quick Start: getting-started/quickstart.md
  - User Guide:
      - Basics: user-guide/basics.md
      - Advanced: user-guide/advanced.md
  - API Reference: api-reference/index.md

# Avoid deep nesting (max 3 levels)

Version Control

Git workflow:

# Create branch for docs
git checkout -b docs/update-readme

# Make changes
git add docs/
git commit -m "docs: update installation guide"

# Push and create PR
git push origin docs/update-readme

.gitignore:

# MkDocs
site/

# Python
__pycache__/
*.pyc
venv/

# IDE
.vscode/
.idea/

Troubleshooting

Common Issues

Build Fails on Read the Docs

Check: 1. .readthedocs.yaml exists 2. requirements.txt has all dependencies 3. Python version specified correctly

Debug:

# .readthedocs.yaml
build:
  os: ubuntu-22.04
  tools:
    python: "3.11"
  apt_packages:
    - graphviz  # If needed

Issue: Broken internal links

Solution:

# Use relative paths
[Installation](getting-started/installation.md)

# Not absolute paths
[Installation](/docs/getting-started/installation.md)

Images Not Loading

Issue: Images don't appear

Solution:

# Correct path (relative to docs/)
![Logo](assets/images/logo.png)

# Not
![Logo](/assets/images/logo.png)

Theme Not Applied

Issue: Material theme not working

Solution:

# Reinstall theme
pip install --upgrade mkdocs-material

# Check mkdocs.yml
theme:
  name: material  # Not 'mkdocs-material'

Search Not Working

Issue: Search returns no results

Solution:

plugins:
  - search:
      lang: en

Rebuild: mkdocs build --clean

Build Warnings

Issue: Warnings during build

Solution:

# View warnings
mkdocs build --verbose

# Strict mode (fail on warnings)
mkdocs build --strict

Performance Issues

Slow builds:

# Disable minification during development
plugins:
  - search
  # - minify  # Comment out

# Reduce extensions
markdown_extensions:
  - toc
  - admonition
  # Comment out heavy extensions

Large sites:

# Use instant loading
theme:
  features:
    - navigation.instant

Quick Reference

Essential Commands

mkdocs new project        # Create new project
mkdocs serve             # Start dev server
mkdocs build             # Build static site
mkdocs gh-deploy         # Deploy to GitHub Pages
mkdocs --version         # Check version

Minimal mkdocs.yml

site_name: My Docs
theme:
  name: material
nav:
  - Home: index.md
  - About: about.md

Minimal .readthedocs.yaml

version: 2
mkdocs:
  configuration: mkdocs.yml
python:
  install:
    - requirements: requirements.txt

requirements.txt

mkdocs>=1.5.0
mkdocs-material>=9.4.0

Additional Resources

Happy documenting! 📚✨