Welcome to the world of documentation with MkDocs! If you're looking for a simple, fast, and beautiful way to create project documentation, you've come to the right place. This comprehensive guide will walk you through everything you need to know to get started with MkDocs, from installation to deployment, even if you're a complete beginner.
Tired of Postman? Want a decent postman alternative that doesn't suck?
Apidog is a powerful all-in-one API development platform that's revolutionizing how developers design, test, and document their APIs.
Unlike traditional tools like Postman, Apidog seamlessly integrates API design, automated testing, mock servers, and documentation into a single cohesive workflow. With its intuitive interface, collaborative features, and comprehensive toolset, Apidog eliminates the need to juggle multiple applications during your API development process.
Whether you're a solo developer or part of a large team, Apidog streamlines your workflow, increases productivity, and ensures consistent API quality across your projects.
Introduction to MkDocs
What is MkDocs?
MkDocs is a static site generator specifically designed for building project documentation. Unlike complex systems that require databases or server-side scripting, MkDocs takes your documentation source files, written in Markdown, and a single YAML configuration file, and outputs a clean, modern, and fully static website. This website can then be hosted on virtually any web server.
The core philosophy behind MkDocs is simplicity. It aims to make the process of writing and maintaining documentation as straightforward as possible, allowing developers and technical writers to focus on creating quality content rather than wrestling with complicated tools. Imagine writing your content in a straightforward text format and having MkDocs transform it into a professional-looking website with navigation, themes, and search capabilities, all without needing to write any HTML or JavaScript yourself (unless you want to!).
Why Use MkDocs?
There are several compelling reasons to choose MkDocs for your documentation needs:
- Simplicity: MkDocs is incredibly easy to set up and use. With just a few commands, you can have a new project up and running. The learning curve is gentle, especially if you're already familiar with Markdown.
- Markdown-centric: Content is written in Markdown, a lightweight markup language that is easy to learn and widely used. This allows for a clean separation of content and presentation. You write in plain text, and MkDocs handles the styling.
- Themes: MkDocs supports theming, allowing you to change the look and feel of your documentation site with ease. It comes with a couple of built-in themes, and many excellent third-party themes (like the popular Material for MkDocs) are available, offering a wide range of styles.
- Extensibility with Plugins: Functionality can be extended using a rich ecosystem of plugins. Whether you need advanced search capabilities, blog features, versioning, or integration with other tools, there's likely a plugin for it.
- Python-based: Being a Python application, MkDocs is cross-platform (Windows, macOS, Linux) and integrates well within Python-based development environments. If you're a Python developer, it feels right at home.
- Live Preview Server: MkDocs includes a built-in development server that automatically reloads your site in the browser whenever you make changes to your documentation or configuration. This provides an excellent real-time preview of your work, speeding up the writing and editing process significantly.
- Static Output: The final output is a set of static HTML, CSS, and JavaScript files. This means your documentation site is inherently fast, secure (no server-side code to exploit), and can be hosted anywhere – from free services like GitHub Pages to robust platforms like Amazon S3 or your own dedicated server.
- Great for Project Documentation: Its structure and features are particularly well-suited for software projects, API documentation, technical guides, user manuals, and knowledge bases.
Who is MkDocs for?
MkDocs is an excellent choice for:
- Software Developers: To document libraries, frameworks, APIs, and applications.
- Technical Writers: Who need a straightforward tool to produce well-structured and maintainable documentation.
- Open Source Projects: Many open-source projects use MkDocs for its ease of use and seamless integration with platforms like GitHub Pages.
- Teams: Looking for a collaborative documentation solution where content can be managed using version control (like Git).
- Anyone needing a simple way to create a static website from Markdown content, even beyond traditional "documentation." Think personal blogs, course materials, or internal wikis.
If you value ease of use, speed, the ability to write in Markdown, and the benefits of a static site, MkDocs is likely a great fit for you.
Prerequisites
Before you dive into installing and using MkDocs, let's ensure you have the necessary tools and basic knowledge:
1. Python and pip
MkDocs is built with Python, and you'll need Python installed on your system to run it. Along with Python, you'll need pip, the Python package installer, which is typically included with modern Python installations.
-
Checking your Python version: Open your terminal or command prompt and type:
python --versionOr, if you have Python 3 installed and it's aliased as
python3:
python3 --versionMkDocs generally requires a recent version of Python. Python 3.8 or newer is recommended for the latest MkDocs features and compatibility.
-
Checking your pip version: In your terminal, type:
pip --versionOr, for Python 3, if
pipis aliased aspip3:
pip3 --versionIf you're using Python environments (like
venvorconda), make sure you check the versions within your active environment.
If you don't have Python or pip, you'll need to install them first.
2. Basic Command-Line Knowledge
You'll be interacting with MkDocs primarily through your system's command-line interface (CLI) – such as Terminal on macOS/Linux or Command Prompt/PowerShell on Windows. You should be comfortable with basic commands like:
- Navigating directories (
cd <directory-name>) - Listing directory contents (
lson macOS/Linux,diron Windows) - Running executable commands
A little familiarity here will go a long way.
3. Text Editor
You'll need a good text editor to write your documentation in Markdown and to edit the MkDocs configuration file (mkdocs.yml). Some popular choices include:
- Visual Studio Code (VS Code): Free, feature-rich, excellent Markdown support, and integrated terminal.
- Sublime Text: Fast, powerful, and highly customizable.
- Atom: Another popular open-source editor.
- Notepad++ (Windows): A lightweight and capable editor for Windows users.
- Vim or Emacs: For users comfortable with these powerful, terminal-based editors.
Any plain text editor will work, but one with Markdown syntax highlighting and possibly a live preview feature can make the writing experience more pleasant.
Installation
Once you have the prerequisites in place, installing MkDocs is straightforward.
Installing Python and pip (If you don't have them)
If you discovered you don't have Python or pip, here's a brief guide:
- Installing Python:
- Go to the official Python website: python.org/downloads/
- Download the installer appropriate for your operating system (Windows, macOS, Linux).
- Run the installer.
- Important for Windows users: During installation, make sure to check the box that says "Add Python to PATH" or "Add Python X.Y to PATH". This is crucial as it allows you to run
pythonandpipcommands directly from your command prompt. If you miss this, you might need to manually add Python's installation and Scripts directories to your system's PATH environment variable. (The MkDocs documentation often includes an image here showing the checkbox in the Windows Python installer.)
- Important for Windows users: During installation, make sure to check the box that says "Add Python to PATH" or "Add Python X.Y to PATH". This is crucial as it allows you to run
-
Installing/Upgrading pip:
- Modern versions of Python (Python 3.4+) usually come with pip pre-installed.
-
If you have an older version of pip, or if it's missing, it's a good idea to upgrade/install it. First, try upgrading:
python -m pip install --upgrade pip(You might need
python3instead ofpythonorpip3instead ofpipdepending on your system setup). -
If pip is not installed for some reason, you can download
get-pip.pyfrom bootstrap.pypa.io/get-pip.py. Save this file, navigate to the directory where you downloaded it using your terminal, and run:
python get-pip.py
Installing MkDocs using pip
With Python and pip ready, you can install MkDocs with a single command. It's generally recommended to install Python packages in a virtual environment to avoid conflicts between projects, but for a first-time global install, you can run:
pip install mkdocs
If you're using Python 3 and pip might default to an older Python 2 on your system (less common now), you might need:
pip3 install mkdocs
Or, to be very explicit about using your current Python's pip module:
python -m pip install mkdocs
This command will download MkDocs and its necessary dependencies from the Python Package Index (PyPI) and install them into your Python environment.
Note for Windows users: If commands like mkdocs are not recognized after installation (and you've already opened a new command prompt window), you likely need to ensure that Python's Scripts directory (e.g., C:\Users\YourUser\AppData\Local\Programs\Python\Python3X\Scripts) is in your system's PATH environment variable. Recent Python installers often provide an option to do this automatically or include a script (e.g., sometimes found in C:\PythonXX\Tools\Scripts\win_add2path.py) that you can run.
Verifying the Installation
To confirm that MkDocs has been installed correctly, open a new terminal window (this ensures it picks up any PATH changes made during installation) and run:
mkdocs --version
You should see output similar to this (the version numbers might differ depending on when you install):
mkdocs, version 1.6.0 from /path/to/your/python/site-packages/mkdocs (Python 3.X)
If you see this, congratulations! MkDocs is installed and ready to go.
If you encounter issues, double-check your Python and pip installation, ensure they are correctly added to your system's PATH, and consult the "Troubleshooting" section later in this guide or the official MkDocs Installation Guide provided within the MkDocs documentation itself.
Getting Started: Your First MkDocs Project
Now for the exciting part – creating your first documentation site with MkDocs!
Creating a New Project
MkDocs provides a handy command to scaffold a new project with a basic structure. Open your terminal, navigate to the directory where you want to create your project (e.g., your Desktop or a projects folder), and run:
mkdocs new my-project
Replace my-project with the desired name for your project folder. This command will create a new directory with that name.
Next, navigate into your newly created project directory:
cd my-project
Let's take a look at the structure MkDocs has created for you. Inside your my-project directory, you will find:
- A file named
mkdocs.yml. - A directory named
docs.- Inside the
docsdirectory, there is a file namedindex.md.
- Inside the
So, to visualize the contents of my-project/:
my-project/
mkdocs.yml (This is your main configuration file)
docs/ (This folder holds all your documentation pages)
index.md (This is the starting page for your site)
This simple structure is all you need to get started.
Understanding the Project Structure
Let's break down these components:
mkdocs.yml(Configuration File):
This is the control center for your MkDocs project. It's a YAML (YAML Ain't Markup Language) file, which is a human-readable data serialization standard. You'll use this file to set various options for your site, such as its name, navigation structure, theme, plugins, and much more. The only required setting in this file issite_name.-
docsDirectory (Your Documentation Source):
This is where you'll spend most of your time writing. It's a folder that contains all your content files.- Each Markdown file (those ending with
.md) that you place in thisdocsdirectory (or any sub-folders you create withindocs) will typically be converted by MkDocs into a corresponding HTML page on your final website. -
index.mdfile: Theindex.mdfile within thedocsdirectory is special. It is treated as the main homepage for your entire site (e.g., if your site isyour-site.com,docs/index.mdbecomesyour-site.com/index.html). - Index files in subdirectories: If you create a sub-folder inside
docs, saydocs/guide/, and place anindex.mdfile there (i.e.,docs/guide/index.md), that page will become the main page for the/guide/section of your site. - Using
README.md: Alternatively, you can name your index pagesREADME.mdinstead ofindex.md(e.g.,docs/README.mdordocs/guide/README.md). This is a common convention, especially if you're hosting your documentation's source code on platforms like GitHub, which automatically display the content ofREADME.mdfiles when browsing a directory. MkDocs is smart enough to recognizeREADME.mdas an index page and will render it asindex.htmlfor the website. If both anindex.mdand aREADME.mdfile exist in the same directory, MkDocs will useindex.md.
- Each Markdown file (those ending with
Writing Your First Page (Basic Markdown)
Let's open the docs/index.md file (located inside the docs folder) in your text editor. By default, it contains some helpful placeholder content:
# Welcome to MkDocs
For full documentation visit [mkdocs.org](https://www.mkdocs.org).
## Commands
* `mkdocs new [dir-name]` - Create a new project.
* `mkdocs serve` - Start the live-reloading docs server.
* `mkdocs build` - Build the documentation site.
* `mkdocs -h` - Print help message and exit.
## Project layout
mkdocs.yml # The configuration file.
docs/
index.md # The documentation homepage.
... # Other markdown pages, images and other files.
This is standard Markdown. Let's personalize it. Modify the first line (the main heading) to something like:
# My Awesome Project Documentation
And perhaps add a sentence below it:
# My Awesome Project Documentation
This is the official documentation for My Awesome Project. Find everything you need here!
Save the file.
Serving Your Documentation Locally
One of the most powerful and convenient features of MkDocs is its built-in development server. This server does two things:
- It builds your documentation from your Markdown files and configuration.
- It serves these built files locally on your computer so you can view them in a web browser. Crucially, it also watches your source files for changes. When you save a change, it automatically rebuilds the site and refreshes your browser.
The MkDocs Development Server (mkdocs serve)
Make sure you are in the root directory of your project (the one containing the mkdocs.yml file and the docs folder). Then, run the following command in your terminal:
mkdocs serve
You'll see output similar to this:
INFO - Building documentation...
INFO - Cleaning site directory
INFO - Documentation built in 0.12 seconds
INFO - [11:45:10] Watching paths for changes: 'docs', 'mkdocs.yml'
INFO - [11:45:10] Serving on http://127.0.0.1:8000/
This output tells you:
- MkDocs has built your site.
- It's watching the
docsdirectory and yourmkdocs.ymlfile for any modifications. - Your site is now being served locally.
Accessing Your Site in the Browser
Open your web browser (like Chrome, Firefox, Safari, or Edge) and navigate to the address shown in the terminal output, which is usually:
You should now see your documentation site! It will reflect the changes you made to docs/index.md, with your new heading and introductory sentence.
Live Reloading in Action
Let's test the live reloading feature. Keep the mkdocs serve command running in your terminal and your browser window displaying your local site open.
- Go back to your text editor and open
docs/index.mdagain. - Change the initial heading to something else, for example:
My Super Cool Project Docs - V2. - Add a new line of text:
This is a new update! - Save the
docs/index.mdfile.
Switch back to your browser. You should see that the page has automatically reloaded, and your new heading and text are displayed almost instantly! The terminal running mkdocs serve will also show activity, indicating it detected a change and rebuilt the site.
This live reloading also works for changes to the mkdocs.yml configuration file. Let's try it:
-
Open
mkdocs.ymlin your text editor. It should currently look something like this (the defaultsite_namemight vary slightly):
site_name: My Docs -
Change the
site_nametoMy Super Cool Project.
site_name: My Super Cool Project Save the
mkdocs.ymlfile.
Your browser will reload again, and you'll see the site title (usually displayed in the header of the page or in the browser tab) update to "My Super Cool Project".
The development server is an invaluable tool for writing documentation, providing instant feedback on your changes and significantly speeding up the iteration process.
To stop the development server, go back to your terminal window where mkdocs serve is running and press Ctrl+C (this works on Windows, macOS, and Linux).
Configuring Your MkDocs Site (mkdocs.yml)
The mkdocs.yml file is where you define the overall structure, appearance, and behavior of your documentation site. It uses YAML syntax, which is human-readable and relies on indentation (using spaces, typically two spaces per level, not tabs!) to define structure and hierarchy.
Here's an overview of some of the most common and important configuration options:
Basic Site Information
These settings define the core identity of your documentation.
-
site_name: (Required) This is the main title for your documentation site. It's prominently displayed, often in the site header and in browser tabs.
site_name: My Awesome Project -
site_url: The full, canonical URL where your site will be hosted once deployed (e.g.,https://username.github.io/my-awesome-project/). This is important for:- Generating correct absolute links if needed.
- Search engine optimization (SEO) by providing a canonical link tag in your HTML.
- Ensuring that the
mkdocs servecommand correctly mimics the subdirectory structure if your site is hosted in one (e.g., ifsite_url: https://example.com/docs/, thenmkdocs servewill serve pages fromhttp://127.0.0.1:8000/docs/). If you are only viewing files locally withfile://(not recommended for full functionality), you might set this to an empty string"".
site_url: https://your-username.github.io/my-project-repo/ -
site_author: Your name or the name of your organization. Some themes may display this, often in the footer or meta tags.
site_author: The Awesome Team -
site_description: A brief description of your site. This is often used in HTML<meta>tags for search engine results.
site_description: 'Comprehensive documentation for My Awesome Project, covering installation, usage guides, API details, and more.' -
repo_url: If your project's source code is hosted on a platform like GitHub, GitLab, or Bitbucket, provide the full URL to the repository here. Many themes will use this to display a link to your repository (e.g., a "View on GitHub" button).
repo_url: https://github.com/your-username/my-awesome-project -
repo_name: The display name for the repository link (e.g., "GitHub", "GitLab", "Source Code"). Ifrepo_urlpoints to a known host (GitHub, GitLab, Bitbucket), this often defaults correctly (e.g., to "GitHub").
repo_name: View on GitHub -
edit_uri: This helps construct the "Edit this page" link that many themes provide. This link allows users to directly jump to the source Markdown file in your repository to suggest changes or fix typos. This is incredibly useful for collaborative documentation.- If your
repo_urlis a GitHub, GitLab or Bitbucket URL, MkDocs often auto-configures a sensible default (e.g.,edit/master/docs/for GitHub, assuming your documentation is in adocs/folder on themasterbranch). -
To point to a different branch (e.g.,
mainwhich is now common) or if your documentation isn't in a/docs/subdirectory at the root of the repo:
# Example for GitHub, editing the 'main' branch, docs in a 'docs/' folder edit_uri: edit/main/docs/ # If your docs are in the root of the repo (not a 'docs/' subfolder) # edit_uri: edit/main/ If you don't want an "Edit this page" link, you can set
edit_urito an empty string:edit_uri: ""-
For more complex URL structures, you can use
edit_uri_template. This offers more flexibility by allowing placeholders. For instance, for a GitHub Wiki:
repo_url: 'https://github.com/project/repo/wiki' edit_uri_template: '{path_noext}/_edit' # '{path_noext}' is the path to the file without extension
- If your
-
copyright: A copyright notice, often displayed in the site footer by themes.
copyright: Copyright © 2024 My Awesome Company Ltd. -
docs_dir: The directory containing your Markdown documentation files. Defaults to'docs/'. You usually don't need to change this unless you have a specific reason.
# docs_dir: 'documentation_sources' # Example if you renamed your docs folder -
site_dir: The directory where the static HTML site will be built. Defaults to'site/'. This is the folder you'll upload to your web host. It's common practice to add this directory to your.gitignorefile if you're using Git.
# site_dir: 'public_html' # Example if you want to build to a different folder
Navigation (nav)
The nav setting allows you to define the structure, order, and titles of your site's main navigation menu. If you omit the nav setting entirely, MkDocs will automatically discover all Markdown files in your docs_dir and create a navigation menu. This auto-generated menu is sorted alphanumerically by file name (with index.md or README.md files appearing first within their respective directories).
For more control and a custom-ordered, human-friendly navigation, define the nav manually:
-
Simple List of Pages:
Each item in the list is a mapping ofTitle In Navigation: 'path/to/markdownfile.md'. The paths are relative to yourdocs_dir.
nav: - 'Home': 'index.md' - 'About Us': 'about.md' - 'Installation Guide': 'installation.md' - 'User Manual': 'usage.md' -
Nested Navigation (Sections and Sub-pages):
You can create sections in your navigation by nesting lists.
nav: - 'Home': 'index.md' - 'User Guide': # This becomes a section title - 'Introduction': 'user-guide/introduction.md' - 'Getting Started': 'user-guide/getting-started.md' - 'Advanced Features': 'user-guide/advanced.md' - 'API Reference': # Another section - 'Module A': 'api/module-a.md' - 'Module B': 'api/module-b.md' - 'Classes': - 'MyClass': 'api/classes/myclass.md' - 'OtherClass': 'api/classes/otherclass.md' - 'About': 'about.md'In this example, "User Guide" and "API Reference" are top-level sections. "Classes" is a sub-section under "API Reference". Note that a section title (like "User Guide") does not link to a page itself; it's purely a container for child pages or further sub-sections.
-
Linking to External Sites:
You can include external links directly in your navigation:
nav: - 'Home': 'index.md' - 'Our Company Website': 'https://example.com' - 'Community Forum': 'https://discuss.example.com' Hiding Pages from Navigation:
Any Markdown files present in yourdocsdirectory that are not explicitly listed in a manualnavconfiguration will still be built into HTML pages and will be accessible if someone knows their direct URL. However, they won't appear in the main site navigation menu, nor will they be included in the automatic "next" and "previous" page links that some themes provide. This can be useful for standalone pages or drafts.
Theme Configuration (theme)
MkDocs allows you to change the entire appearance of your site using themes. This is one of its most powerful customization features.
-
Setting the Theme Name:
MkDocs comes with two built-in themes:-
mkdocs: The default theme. It's clean and functional. -
readthedocs: A theme that mimics the style of the popular Read the Docs documentation hosting service.
To use a built-in theme, you can use a simple form:
theme: mkdocsOr:
theme: readthedocsYou can also use numerous excellent third-party themes. One of the most popular is Material for MkDocs. To use a third-party theme, you first need to install it (usually via
pip, e.g.,pip install mkdocs-material). Then, you specify its name:
theme: name: material # 'name' is required when providing other theme options -
-
Customizing Theme Options:
Many themes offer their own set of configuration options that allow you to fine-tune their appearance and behavior. These options are typically nested under thethemekey in yourmkdocs.yml. You'll need to consult the specific theme's documentation for available options.For example, for the built-in
mkdocstheme:
theme: name: mkdocs # Navigation bar style: can be 'primary' (blue), 'dark', or 'light' nav_style: primary # Default color mode: 'light', 'dark', or 'auto' (tries to match system preference) color_mode: light # Allow user to toggle color mode via a UI switch: true or false user_color_mode_toggle: true # Enable/disable code highlighting with highlight.js (default is true) highlightjs: true # Style for highlight.js in light mode (see highlight.js docs for style names) hljs_style: github # Style for highlight.js in dark mode hljs_style_dark: github-dark # Add support for more programming languages in highlight.js if they aren't common hljs_languages: - yaml - rust - go # Google Analytics (GA4) configuration analytics: gtag: 'G-YOURTRACKINGID' # Replace with your Google Analytics 4 Measurement ID # Maximum navigation depth to display in the sidebar navigation_depth: 2 # Locale for theme translations (e.g., for "Next", "Previous" buttons) # locale: 'en' # 'en' is English, 'fr' for French, etc. Requires mkdocs[i18n]For the built-in
readthedocstheme:
theme: name: readthedocs # Show/hide the homepage link in the sidebar navigation include_homepage_in_sidebar: true # Location of previous/next page buttons: 'bottom', 'top', 'both', or 'none' prev_next_buttons_location: bottom # Maximum navigation depth in the sidebar navigation_depth: 4 # If true, collapses navigation to only show current page's sections and siblings collapse_navigation: true # Similar highlight.js settings as mkdocs theme highlightjs: true hljs_languages: - python - json # Google Analytics (GA4) analytics: gtag: 'G-YOURTRACKINGID' # locale: 'en'For a third-party theme like Material for MkDocs, the options are extensive and powerful, covering color palettes, fonts, features toggles, social links, and much more. You'd refer to its official documentation. Example snippet:
theme: name: material palette: scheme: default # Can be 'default' (light) or 'slate' (dark) primary: indigo accent: blue font: text: Roboto code: Roboto Mono features: - navigation.tabs - navigation.top - search.suggest # ... many more options -
use_directory_urls:
This setting controls the URLs generated for your pages.- If
true(default): Pages will have "clean" URLs, e.g.,mysite.com/about/(which servesmysite.com/about/index.html). This is generally preferred for nicer looking URLs and works well with most web servers. - If
false: Pages will have URLs ending in.html, e.g.,mysite.com/about.html. This can be necessary for some hosting environments or when viewing files directly usingfile://protocol (though usingmkdocs serveis always better for local viewing).
use_directory_urls: true - If
Markdown Extensions (markdown_extensions)
MkDocs uses the Python-Markdown library to convert your Markdown files to HTML. This library can be enhanced with various extensions that add new syntax features or modify existing behavior. You can enable these extensions in your mkdocs.yml.
Some useful extensions include:
-
toc(Table of Contents): Generates a table of contents from your document headers. Often enabled by default or by themes.-
permalink: true: Adds anchor links to headers.
-
-
admonition: Allows you to create special highlighted blocks like "note," "warning," "tip," etc. -
codehilite(CodeHilite): Provides syntax highlighting for code blocks if Pygments is installed (pip install pygments). Themes might use this or their own JavaScript-based highlighting.-
guess_lang: false: Prevents guessing language if not specified, which can be more predictable. -
linenums: true: Can add line numbers to code blocks.
-
-
meta(Meta-Data): Allows you to define metadata (like page title or description) at the top of your Markdown files. -
footnotes: Adds support for Markdown footnotes. -
attr_list: Allows adding HTML attributes (like CSS classes or IDs) to Markdown elements. -
tables: Standard Markdown tables. -
pymdownx.*: The PyMdown Extensions suite provides many powerful additions like better code highlighting (SuperFences), task lists, emoji support, progress bars, and much more. You'd installpymdown-extensionsvia pip.
Example configuration:
markdown_extensions:
- admonition
- codehilite:
guess_lang: false
- toc:
permalink: true
- footnotes
- meta
- attr_list
# Example using a PyMdown Extension (requires pip install pymdown-extensions)
- pymdownx.superfences
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
The exact extensions and their configurations depend on your needs and what your chosen theme supports or expects.
Plugins (plugins)
Plugins allow you to extend MkDocs' functionality beyond what's available through themes or Markdown extensions. There's a wide variety of community-contributed plugins. Some common uses for plugins include:
- Enhanced search (e.g.,
searchplugin is built-in, but others exist) - Adding blog-like features
- Generating sitemaps or social cards
- Minifying HTML/CSS/JS
- Adding support for diagrams (e.g., Mermaid)
- Version control integration for documentation versioning
You first install a plugin (usually via pip), then enable and configure it in the plugins section of mkdocs.yml.
The built-in search plugin is enabled by default if not explicitly overridden by an empty plugins list.
plugins:
- search # This is often implicitly enabled
# Example: a plugin for minifying HTML
# - minify:
# minify_html: true
# Example: a plugin for adding social cards (requires pip install mkdocs-social-cards)
# - social
Always refer to the specific plugin's documentation for installation and configuration instructions.
This covers many of the fundamental mkdocs.yml settings. As you work more with MkDocs, you'll discover more advanced options and those specific to the themes and plugins you choose.
Writing Documentation with Markdown
MkDocs uses Markdown for writing documentation content. If you're new to Markdown, it's a simple plain text formatting syntax that's designed to be easy to read and write, and it converts cleanly to HTML.
Here are some common Markdown elements you'll use:
-
Headings:
# Heading 1 (Largest) ## Heading 2 ### Heading 3 #### Heading 4 ##### Heading 5 ###### Heading 6 (Smallest) Paragraphs: Just type text. Separate paragraphs with a blank line.
-
Emphasis:
*This text will be italic.* _This will also be italic._ **This text will be bold.** __This will also be bold.__ ***This text will be bold and italic.*** -
Lists:
-
Unordered Lists: Use asterisks, plus signs, or hyphens.
* Item 1 * Item 2 * Sub-item 2a * Sub-item 2b - Item 3 -
Ordered Lists: Use numbers followed by periods.
1. First item 2. Second item 3. Third item 1. Sub-item 3a 2. Sub-item 3b
-
-
Links:
[Link text](https://www.example.com "Optional link title")For internal links to other pages in your MkDocs site, see the "Internal Linking" section below.
-
Images:
The path is typically relative to your
docsdirectory. So, if you have an image atdocs/img/logo.png, you'd link it as. -
Code:
-
Inline Code: Wrap code with backticks.
Use the `mkdocs serve` command. -
Code Blocks (Fenced Code Blocks): Use triple backticks, and optionally specify the language for syntax highlighting.
python
def hello():
print("Hello, MkDocs!")
javascript
console.log("Hello, MkDocs!");
Syntax highlighting usually requires a theme that supports it or a Markdown extension like CodeHilite with Pygments installed.
-
-
Blockquotes:
markdown > This is a blockquote. > It can span multiple lines. -
Tables:
markdown | Header 1 | Header 2 | Header 3 | |----------|----------|----------| | Row 1, Col 1 | Row 1, Col 2 | Row 1, Col 3 | | Row 2, Col 1 | Row 2, Col 2 | Row 2, Col 3 |Requires the
tablesMarkdown extension (often enabled by default). -
Horizontal Rules:
markdown --- *** ___ -
Admonitions (Requires
admonitionextension):
These are special highlighted boxes for notes, warnings, tips, etc.markdown !!! note This is a note. Useful for important information. !!! warning "Don't Forget!" This is a warning with a custom title. !!! tip "Pro Tip" Here's a helpful tip. !!! danger "Critical Alert" This is a danger admonition.Common types include:
note,attention,caution,danger,error,hint,important,tip,warning. Themes usually style these distinctively.
Internal Linking
MkDocs makes it easy to link between pages within your documentation site.
-
Linking to Other Markdown Pages:
When linking to another Markdown page, always use the relative path to the.mdfile from the current file, or an absolute path from thedocs_dir. MkDocs will automatically convert these.mdlinks to the correct HTML links during the build process.Suppose your
docsdirectory structure is:docs/ index.md intro/ overview.md installation.md reference/ api.md-
From
docs/index.mdto link tooverview.md:markdown [Read the Overview](intro/overview.md) -
From
docs/intro/overview.mdto link toinstallation.md(in the same directory):markdown [Next: Installation](installation.md) -
From
docs/intro/installation.mdto link back tooverview.md:markdown [Previous: Overview](overview.md) -
From
docs/intro/overview.mdto link toapi.md(in a different directory):markdown [API Reference](../reference/api.md) -
You can also use absolute paths from the
docsroot:
Fromdocs/intro/overview.mdtodocs/reference/api.md:markdown [API Reference](/reference/api.md) (Note: leading slash might not always be needed if your site_url is not set or you are not using directory urls. Test this.)Generally, relative links are safer and more portable.
-
-
Linking to Sections within a Page (Anchors):
If you have headers in your Markdown files, themes often automatically create anchor links for them. You can link directly to these sections.
The anchor is usually a lowercase version of the header text, with spaces replaced by hyphens, and special characters removed. For example, a header## My Awesome Sectionmight have an anchor#my-awesome-section.To link to a section in the same page:
markdown [Jump to Awesome Section](#my-awesome-section)To link to a section in a different page (
another-page.md):markdown [Details in Another Page](another-page.md#section-name-there)Enabling
toc: permalink: trueinmarkdown_extensionsis a good way to ensure these anchors are explicitly created and visible. -
Linking to Images and Media:
Place your images and other static media (like PDFs) inside yourdocsdirectory (often in a subdirectory likedocs/img/ordocs/assets/). Link to them using paths relative to thedocsdirectory root or relative to the current Markdown file.If you have
docs/img/screenshot.png:markdown Or, from a file like
docs/features/feature-a.md, todocs/img/feature-a-diagram.png:markdown MkDocs will copy these files to your
sitedirectory during the build process, maintaining their relative paths.
Structuring Your Documentation
A well-structured documentation site is easy to navigate and understand.
Adding More Pages
To add a new page, simply create a new Markdown file (e.g., about.md, contact.md) within your docs directory or one of its subdirectories.
For example, to add an "About Us" page:
- Create a file named
about.mdinside yourdocsfolder. -
Add some Markdown content to
docs/about.md:markdown # About Us We are a team dedicated to making awesome projects! -
If you are managing navigation manually in
mkdocs.ymlusing thenavsetting, add the new page there:yaml site_name: My Super Cool Project nav: - 'Home': 'index.md' - 'About Us': 'about.md' # Added new pageIf you are not using a manual
navsetting, MkDocs will automatically detectabout.mdand add it to the navigation (usually sorted alphanumerically).
Save your files, and if mkdocs serve is running, your site will update, and you should see "About Us" in the navigation.
Creating Subdirectories for Sections
For larger documentation sites, it's good practice to organize your Markdown files into subdirectories within the docs folder. This mirrors how you might structure sections in your nav configuration.
Example structure:
docs/
index.md
user-guide/ (Folder for user guide section)
introduction.md
installation.md
troubleshooting.md
api-reference/ (Folder for API docs)
endpoints.md
authentication.md
about.md
You would then reflect this structure in your nav setting in mkdocs.yml:
yaml
nav:
- 'Home': 'index.md'
- 'User Guide':
- 'Introduction': 'user-guide/introduction.md'
- 'Installation': 'user-guide/installation.md'
- 'Troubleshooting': 'user-guide/troubleshooting.md'
- 'API Reference':
- 'Endpoints': 'api-reference/endpoints.md'
- 'Authentication': 'api-reference/authentication.md'
- 'About': 'about.md'
This keeps your source files organized and your navigation configuration clean.
Building Your Site (mkdocs build)
While mkdocs serve is great for local development and previewing, it doesn't (by default) create a distributable version of your site. For that, you need the mkdocs build command.
When you're ready to deploy your site or want to inspect the final static files, run:
bash
mkdocs build
This command does the following:
- Reads your
mkdocs.ymlconfiguration. - Processes all your Markdown files from the
docs_dir. - Applies the theme and any customizations.
- Outputs the complete static HTML, CSS, JavaScript, images, and other assets into the
site_dir(which defaults to a folder namedsite/in your project root).
After the build completes, you'll have a site/ directory. Its contents are your entire website.
Example contents of site/:
site/
index.html
about/
index.html (if you have docs/about.md and use_directory_urls: true)
css/
theme.css
custom.css (if you added extra_css)
js/
theme.js
img/
logo.png
search/
search_index.json (for the search functionality)
sitemap.xml (often generated for SEO)
... (other files and folders depending on your content and theme)
You can open site/index.html in your browser to view the locally built site. However, be aware that if use_directory_urls is true, navigation might not work perfectly when opened via file:// URLs due to browser security restrictions and how clean URLs are handled. It's best to serve the site directory with a simple local web server for accurate testing, or just rely on mkdocs serve for previews.
Cleaning before building:
Sometimes, you might want to ensure a clean build, especially if you've renamed or removed files. The mkdocs build command has a --clean flag:
bash
mkdocs build --clean
This will delete the site_dir before rebuilding, ensuring no old files are left behind. mkdocs serve also cleans by default.
The site/ directory is what you'll deploy to your web hosting provider.
Theming Your Documentation
Themes control the visual appearance and layout of your MkDocs site.
Choosing a Theme
As mentioned in the configuration section, MkDocs has two built-in themes:
-
mkdocs: The default, a Bootstrap-based theme. -
readthedocs: Mimics the Read the Docs style.
To use one, in mkdocs.yml:
yaml
theme: mkdocs
# or
theme: readthedocs
Many third-party themes offer more features and modern designs. Material for MkDocs is exceptionally popular. To use a third-party theme:
- Install it:
pip install mkdocs-material(for Material theme). -
Configure it in
mkdocs.yml:yaml theme: name: material # ... other material theme specific optionsYou can find other themes on the MkDocs Themes wiki page and the MkDocs Catalog.
Deploying Your Site
Since MkDocs generates a fully static site, you have many options for hosting it, many of them free or very low-cost.
1. GitHub Pages
If your project's source code is already hosted on GitHub, GitHub Pages is an excellent and free way to host your documentation. MkDocs has a built-in command to simplify this process: mkdocs gh-deploy.
-
For Project Pages (documentation for a specific repository):
- Make sure your
mkdocs.ymlhas thesite_urlcorrectly set (e.g.,https://your-username.github.io/your-repo-name/). - Ensure your code is committed and pushed to GitHub.
-
From your project root (where
mkdocs.ymlis), run:bash mkdocs gh-deployThis command will:
- Build your site into the
site/directory. - Commit the contents of
site/to a special branch in your repository (usuallygh-pages). - Push this
gh-pagesbranch to GitHub. GitHub will then automatically serve the site from this branch. You might need to enable GitHub Pages in your repository settings (select thegh-pagesbranch as the source).
- Build your site into the
- Make sure your
-
For User or Organization Pages (site for your GitHub user or org, not a specific project):
These sites are served from themasterormainbranch of a specially named repository (e.g.,your-username.github.io).
You'd typically build your MkDocs site in its own repository, then configuremkdocs gh-deployto push to themaster/mainbranch of youryour-username.github.iorepository.bash # Example: deploy to the 'main' branch of the remote 'origin' mkdocs gh-deploy --remote-branch main # Or if deploying from one repo to another: # mkdocs gh-deploy --config-file ../my-docs-source/mkdocs.yml --remote-branch main --remote-name upstream-pages-repoThis is a bit more advanced; refer to MkDocs and GitHub Pages documentation.
-
Custom Domains with GitHub Pages:
GitHub Pages supports custom domains.- Configure your custom domain in your GitHub repository settings.
- Create a file named
CNAMEinside yourdocs/directory. This file should contain only your custom domain (e.g.,docs.example.com) on a single line. MkDocs will copy thisCNAMEfile to the root of your built site, which GitHub Pages requires.
-
Important for
gh-deploy:- Add
site/to your.gitignorefile, as this directory is regenerated on each build. - The
gh-deploycommand overwrites the deployment branch. Don't make manual edits there.
- Add
2. Read the Docs
Read the Docs is a very popular free hosting platform specifically for documentation. It integrates directly with Git repositories (GitHub, GitLab, Bitbucket).
- Sign up for Read the Docs.
- Link your Git repository.
- Configure your project on Read the Docs to use MkDocs.
Read the Docs will then automatically build and deploy your documentation whenever you push changes to your repository. It also handles versioning and PDF generation. You'll need a small configuration file (e.g.,
.readthedocs.yaml) in your repository to tell Read the Docs how to build your project.
3. Other Static Hosting Providers
Since MkDocs produces static files, you can host your site/ directory content on virtually any web host:
- Netlify: Offers excellent free tiers for static sites, CI/CD integration, and more.
- Vercel: Similar to Netlify, great for static sites and serverless functions.
- AWS S3: Host your static site on Amazon S3 for robust, scalable hosting.
- Google Cloud Storage: Similar to S3.
- Firebase Hosting: Google's platform for web and mobile apps, includes static hosting.
- Traditional Shared Hosting or VPS: Simply upload the contents of your
site/directory to your web server's public HTML folder (e.g.,public_html,www,htdocs) using FTP, SCP, or rsync.
The general process is:
- Run
mkdocs buildto generate thesite/directory. - Upload the contents of the
site/directory to your host.
Advanced Topics (A Brief Look)
As you get more comfortable with MkDocs, you might explore:
- Page-Specific Metadata: You can add metadata (like a custom page title or description) at the very top of your Markdown files using YAML front matter, if you have the
metaMarkdown extension enabled:
markdown
---
title: My Custom Page Title
description: A special page about widgets.
template: custom-page-layout.html # Some themes allow per-page templates
---
# Page Content Starts Here
...
This metadata is accessible to themes and plugins.
- Hooks (
hooks.py): MkDocs allows you to run custom Python scripts at different points in the build process. You create ahooks.pyfile in your project root (same level asmkdocs.yml). Example hooks:on_pre_build,on_page_markdown(to modify Markdown before rendering),on_post_build. This is an advanced feature for complex customizations. Thehooks.pyfile you provided in the initial context demonstrates modifying Markdown content for a specific page to dynamically generate a list.
Troubleshooting Common Issues
- Command
mkdocsnot found:- Ensure Python and its Scripts directory are in your system's PATH.
- Try opening a new terminal window after installation.
- Make sure you're in the correct Python environment if using virtual environments.
- Changes not appearing with
mkdocs serve:- Ensure
mkdocs serveis still running in a terminal. - Check the terminal output for any error messages.
- Force a browser refresh (Ctrl+R or Cmd+R), though live reload usually handles this.
- Ensure
- YAML Indentation Errors in
mkdocs.yml:- YAML is very sensitive to indentation. Use spaces, not tabs. Be consistent (e.g., 2 spaces per level).
- Consult a YAML validator if you're stuck.
- Links or Images not working:
- Double-check paths. They are usually relative to the
docs/directory or the current file.
- Double-check paths. They are usually relative to the
- Theme customization not applying:
- Verify paths in
extra_css,extra_javascript, orcustom_dir. - Ensure the
custom_diris correctly specified under thethemekey, alongsidename. - Clear your browser cache if CSS/JS changes aren't showing up immediately.
- Verify paths in
Where to find help:
- Official MkDocs Documentation: mkdocs.org - It's excellent and comprehensive.
- GitHub Issues: Check the MkDocs GitHub repository for reported issues or to ask questions.
- Stack Overflow: Many MkDocs questions have been answered there.
Conclusion
MkDocs is a powerful yet user-friendly tool for creating beautiful and effective documentation. Its simplicity, reliance on Markdown, theming capabilities, and extensibility make it an excellent choice for projects of all sizes. By following this guide, you've learned how to install MkDocs, create and configure a project, write content, customize themes, and deploy your site.
The best way to learn is by doing. Start a new project, experiment with themes and configurations, and explore the rich ecosystem of plugins and Markdown extensions. Happy documenting!

Top comments (0)