Skip to content

Tech

Customizing Your MkDocs Blog 🎨

Once you've set up your MkDocs blog, it's time to personalize it. In this post, I'll cover various customizations, including social media sharing hooks, changing the blog icon and favicon, adding authors, and using tags. These modifications will make your blog more interactive and visually appealing.

All of the steps covered in this guide are available in the MKDocs Documentation or via the superb video tutorials created by James Willett

Adding Social Media Sharing Hooks πŸ”„

To allow users to share your blog posts easily, you can create a socialmedia.py hook. This script appends sharing buttons to each post.

Create the Hook File

Inside your project, create a folder named hooks/ if it doesn't already exist, and then add a file called socialmedia.py:

mkdir hooks
nano hooks/socialmedia.py

Add the Social Media Sharing Code

Paste the following into socialmedia.py:

from textwrap import dedent
import urllib.parse
import re

x_intent = "https://x.com/intent/tweet"
fb_sharer = "https://www.facebook.com/sharer/sharer.php"
include = re.compile(r"posts/.*")

def on_page_markdown(markdown, **kwargs):
    page = kwargs['page']
    config = kwargs['config']
    if not include.match(page.url):
        return markdown

    page_url = config.site_url + page.url
    page_title = urllib.parse.quote(page.title + '\n')

    return markdown + dedent(f"""
    [Share on :simple-x:]({x_intent}?text={page_title}&url={page_url}){{ .md-button }}
    [Share on :simple-facebook:]({fb_sharer}?u={page_url}){{ .md-button }}
    """)

How the Code Works:

  • The script identifies blog post pages using a regular expression (posts/.*)
  • It gets the current page URL and title from MkDocs
  • It adds formatted markdown buttons at the end of your content
  • The buttons link to X (Twitter) and Facebook with pre-filled sharing information

Enable the Hook in mkdocs.yml

Modify mkdocs.yml to include the hook:

hooks:
  - hooks/socialmedia.py

This will append social media sharing buttons to your posts.

Changing the Blog Icon and Favicon πŸ–ΌοΈ

Updating your blog's favicon and site icon enhances branding.

Prepare the Icons

Save your icons in docs/images/ as:

  • favicon.ico (16x16 or 32x32 pixels) - Used by browsers in tabs and bookmarks
  • logo.png (recommended 512x512 pixels) - Displayed in your site header/navigation

Update mkdocs.yml

extra:
  logo: images/logo.png
  favicon: images/favicon.ico

Note: These paths are relative to your docs/ directory, and both settings should be nested under the extra: key in your configuration file.

Restart the Server

Run mkdocs serve to preview the changes.

Adding Authors πŸ‘₯

To attribute posts to different authors, create an authors.yml file.

Create authors.yml

In the docs/ directory of your project, create a file named authors.yml:

matthew:
  name: "Matthew Pollock"
  email: "matthew@example.com"
  website: "https://matthewblog.com"

team:
  name: "Blog Team"
  website: "https://teamwebsite.com"

squidfunk:
  name: "SquidFunk"
  website: "https://squidfunk.github.io/"

Modify each post's metadata:

authors:
  - matthew
  - team

Adding Tags 🏷️

Tags help categorize your blog posts.

Create tags.md

Create a docs/tags.md file. Below are the tags used in this blog:

# Tags
tags:
  - technology
  - learning

Enable Tags in mkdocs.yml

Modify mkdocs.yml:

plugins:
  - tags:
      tags_file: tags.md

Now, you can tag posts like this:

tags:
  - technology
  - learning

Enabling Comments on Blog Posts πŸ’¬

If you want to enable comments on blog posts, follow these steps:

Create the Comments Template

Create a directory overrides/partials/ if it doesn't exist, then add a file called comments.html with your Disqus integration code:

<div id="disqus_thread"></div>
<script>
  var disqus_config = function () {
    this.page.url = window.location.href;
    this.page.identifier = document.title;
  };
  (function() {
    var d = document, s = d.createElement('script');
    s.src = 'https://your-disqus-name.disqus.com/embed.js';
    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
  })();
</script>

Note: Replace your-disqus-name with your Disqus shortname, which you can find in your Disqus admin panel after creating a site.

Enable Comments in mkdocs.yml

extra:
  comments: true

Restart MkDocs and test:

mkdocs serve

Theme Customization 🎭

The Material theme offers extensive customization options for colors, fonts, and more.

Custom Color Scheme

Add this to your mkdocs.yml:

theme:
  name: material
  palette:
    # Light mode
    - media: "(prefers-color-scheme: light)"
      scheme: default
      primary: indigo
      accent: indigo
      toggle:
        icon: material/toggle-switch-off-outline
        name: Switch to dark mode
    # Dark mode
    - media: "(prefers-color-scheme: dark)"
      scheme: slate
      primary: blue
      accent: blue
      toggle:
        icon: material/toggle-switch
        name: Switch to light mode

Custom Fonts

theme:
  font:
    text: Roboto
    code: Roboto Mono

Analytics Integration πŸ“Š

Add analytics to track your blog's performance.

Google Analytics

extra:
  analytics:
    provider: google
    property: G-XXXXXXXXXX

Plausible Analytics

extra:
  analytics:
    provider: plausible
    domain: yourdomain.com

SEO Optimization πŸ”

Improve your blog's search engine visibility.

Add Meta Tags

plugins:
  - meta

Then in each post, add:

meta:
  description: "A detailed guide to customizing MkDocs blogs"
  keywords: mkdocs, blog, customization, web development
  robots: index, follow
  og:image: /assets/social-card.png

Performance Optimization ⚑

Keep your blog fast and responsive.

Image Optimization

  1. Compress all images before adding them to your blog
  2. Use modern formats like WebP
  3. Specify image dimensions in HTML to prevent layout shifts

Lazy Loading

Enable lazy loading of images using the loading="lazy" attribute:

![Alt text](image.jpg){ loading=lazy }

Understanding Your MkDocs Project Structure πŸ“

Once you have created an MkDocs project and added the components listed in the two posts in this series, you'll see a folder structure similar to this:

project-blog/
β”œβ”€β”€ docs/                 # Documentation files (Markdown content)
β”‚   β”œβ”€β”€ index.md          # Homepage of your site
β”‚   β”œβ”€β”€ tags.md           # Tags page for blog posts
β”‚   β”œβ”€β”€ authors.yml       # Defines author metadata
β”‚   β”œβ”€β”€ posts/            # Blog post storage
β”‚   β”‚   β”œβ”€β”€ firstpost.md  
β”‚   β”‚   β”œβ”€β”€ secondpost.md  
β”‚   β”‚   β”œβ”€β”€ thirdpost.md  
β”‚   β”œβ”€β”€ images/           # Store all your images here
β”‚   β”‚   β”œβ”€β”€ logo.png  
β”‚   β”‚   β”œβ”€β”€ favicon.ico
β”œβ”€β”€ hooks/                # Custom MkDocs hooks (like social media sharing)
β”œβ”€β”€ overrides/            # Custom HTML overrides for Material theme
β”‚   β”œβ”€β”€ partials/comments.html  # Comment system (if enabled)
β”œβ”€β”€ mkdocs.yml            # Configuration file for MkDocs
β”œβ”€β”€ requirements.txt      # Python dependencies
β”œβ”€β”€ .gitignore            # Files to exclude from Git

This structure keeps content organized, making it easy to scale your documentation or blog.

Deploying Updates πŸš€

Whenever you make changes, redeploy your site:

mkdocs gh-deploy

This command builds your site and pushes it to the gh-pages branch of your repository.

Troubleshooting Tips πŸ”§

Social Media Buttons Not Showing

  • Ensure your mkdocs.yml has the site_url property set correctly
  • Verify the hook is correctly installed in the hooks/ directory

Favicon Not Displaying

  • Clear your browser cache
  • Ensure the path in mkdocs.yml is correct relative to the docs/ directory

Comments Not Loading

  • Check your browser console for JavaScript errors
  • Verify your Disqus shortname is correct
  • Ensure extra.comments is set to true in mkdocs.yml

Deployment Issues

If mkdocs gh-deploy fails:

# Ensure you have the latest version of MkDocs
pip install --upgrade mkdocs mkdocs-material

# Check your git configuration
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Conclusion πŸŽ‰

With these customizations, your MkDocs blog will be more interactive and visually engaging. The additions of social sharing, comments, better visualization with icons, and proper author attribution will make your blog more professional and user-friendly.

In our next post, we'll cover advanced MkDocs features including content reuse, advanced search configuration, and integration with other tools in your workflow.

Stay tuned for more tips!


πŸ“Œ Published on: 2025-03-09
⏳ Read time: 8 min

Share on Share on

Enhancing My MkDocs Blog with Custom Features πŸš€

Once I set up my MkDocs blog, I wanted to personalize it by adding navigation links, social media icons, an announcement bar, and a custom footer. These enhancements improve user experience, branding, and site functionality. This post walks through each customization step with code examples and configurations.

To provide quick access to key profiles and resources, I added navigation links.

πŸ“ Update mkdocs.yml

nav:
  - Home: index.md
  - Blog: blog.md
  - About: about.md
  - Contact: contact.md
  - GitHub: https://github.com/cloudlabmp
  - LinkedIn: https://linkedin.com/in/matthew-pollock-76831920/
  - Website: https://profile.pollockweb.com

This allows visitors to access my GitHub, LinkedIn, and personal site from the navigation menu.


🌐 Adding Social Media Icons to the Header

Instead of plain text links, I enabled social media icons in the header.

πŸ“ Update mkdocs.yml

extra:
  social:
    - icon: fontawesome/brands/github
      link: https://github.com/cloudlabmp
    - icon: fontawesome/brands/linkedin
      link: https://linkedin.com/in/matthew-pollock-76831920/
    - icon: fontawesome/solid/globe
      link: https://profile.pollockweb.com

These icons now appear in the top-right of the header.


πŸ“’ Enabling the Announcement Bar

A dismissible announcement bar allows for important updates.

πŸ“ Update mkdocs.yml

theme:
  name: material
  features:
    - announce.dismiss

πŸ“ Customize overrides/main.html

{% extends "base.html" %}

{% block announce %}
  <div class="announcement-content">
    <p>Welcome to my blog! Connect with me:</p>
    <a href="https://github.com/cloudlabmp" target="_blank">
      <i class="fab fa-github fa-2x"></i>
    </a>
    <a href="https://www.linkedin.com/in/matthew-pollock-76831920/" target="_blank">
      <i class="fab fa-linkedin fa-2x"></i>
    </a>
  </div>
{% endblock %}

To personalize the footer, I added a copyright notice and aligned social media icons.

πŸ“ Customize overrides/partials/footer.html

{% block content %}
  <div class="custom-footer">
    <div class="custom-footer-left">
      <p>Copyright &copy; 2025 Matthew Pollock</p>
    </div>
    <div class="custom-footer-right">
      <a href="https://github.com/cloudlabmp" target="_blank">
        <i class="fab fa-github"></i>
      </a>
      <a href="https://linkedin.com/in/matthew-pollock-76831920/" target="_blank">
        <i class="fab fa-linkedin"></i>
      </a>
      <a href="https://profile.pollockweb.com" target="_blank">
        <i class="fas fa-globe"></i>
      </a>
    </div>
  </div>
{% endblock %}
/* Custom footer styling */
.custom-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  width: 100%;
  background: var(--md-default-bg-color);
  border-top: 1px solid var(--md-default-fg-color--light);
}

.custom-footer-left {
  text-align: left;
  font-size: 0.9em;
  color: var(--md-default-fg-color);
}

.custom-footer-right {
  display: flex;
  gap: 15px;
}

.custom-footer-right a {
  font-size: 1.8em;
  color: var(--md-default-fg-color);
  transition: transform 0.2s ease-in-out;
}

.custom-footer-right a:hover {
  transform: scale(1.2);
  color: #673AB7; /* Deep Purple (Accent Color) */
}

/* Add padding to the bottom of the page */
.md-content {
  padding-bottom: 40px;
}

πŸŽ‰ Final Results

βœ” Clickable social media icons in the header and footer
βœ” A dismissible announcement bar for updates
βœ” Navigation links to external sites
βœ” A fully customized footer with copyright and icons
βœ” Refined color scheme using deep purple accents

Each of these enhancements has made my MkDocs blog more functional, visually appealing, and user-friendly. If you’re looking to implement similar customizations, these steps should get you started! πŸš€


Share on Share on

Setting Up MkDocs for Your Blog πŸ“

If you're looking for a simple yet powerful way to create and manage your documentation or blog, MkDocs is a fantastic option. MkDocs is a fast, static site generator that's geared towards building project documentation but works wonderfully for blogs too! In this post, I'll walk you through the steps to set up MkDocs with the popular Material theme and get it hosted on GitHub Pages.

All of the steps covered in this guide are available in the MkDocs Documentation or via the superb video tutorials created by James Willett.

Why I Chose MkDocs πŸ€”

After exploring several blogging platforms, I settled on MkDocs for its simplicity, flexibility, and Markdown support. Unlike WordPress or Ghost, MkDocs is lightweight and doesn't require a database. The Material theme provides beautiful out-of-the-box styling, and since everything is in Markdown, I can easily version control my content using Git.

Prerequisites πŸ› οΈ

Before we begin, ensure you have the following installed:

  • Python 3.x – MkDocs is a Python-based tool. You can check if Python is installed by running:
python --version

If Python is not installed, download it from python.org and follow the installation instructions.

  • pip – Python's package manager. It usually comes with Python, but you can verify it with:
pip --version
  • Git – To manage version control and push changes to GitHub. You can install Git from git-scm.com.

Setting Up Your Environment 🌱

It's a good practice to use a virtual environment (venv) when working with Python projects to avoid dependency conflicts:

  1. Navigate to your project directory:
cd /path/to/your/project
  1. Create a virtual environment:
python -m venv venv
  1. Activate the virtual environment:

Choose your OS

venv\Scripts\activate
source venv/bin/activate

Installing MkDocs

Once your virtual environment is activated, install MkDocs:

pip install mkdocs

To verify the installation, run:

mkdocs --version

If you see the installed version displayed, the installation was successful.

Creating a New MkDocs Project πŸ—οΈ

Navigate to the directory where you want to create your blog and run:

mkdocs new my-blog
cd my-blog

This creates a basic MkDocs project structure, including:

  • A default mkdocs.yml configuration file
  • A docs/ directory containing an index.md file

Installing Dependencies βš™οΈ

To enhance your MkDocs site with additional features, create a requirements.txt file in the root of your project:

# Requirements for core
jinja2~=3.0
markdown~=3.2
mkdocs~=1.6
mkdocs-material~=9.5.46
mkdocs-material-extensions~=1.3
pygments~=2.16
pymdown-extensions~=10.2

# Requirements for plugins
babel~=2.10
colorama~=0.4
paginate~=0.5
regex>=2022.4
requests~=2.26

# Additional Material and MkDocs plugins
mkdocs-glightbox~=0.4.0
mkdocs-get-deps~=0.2.0
mkdocs-minify-plugin~=0.8.0
mkdocs-git-committers-plugin-2~=2.4.1
mkdocs-git-revision-date-localized-plugin~=1.3.0
mkdocs-rss-plugin~=1.16.0

Install these dependencies with:

pip install -r requirements.txt

Customizing Your Blog ✨

Basic Configuration

The mkdocs.yml file is the configuration file for your blog. Open it in a text editor and modify it:

site_name: My Tech Blog
site_description: A blog documenting my projects and insights
site_author: Your Name
repo_url: https://github.com/yourusername/my-blog

Adding the Material Theme

The Material theme provides a clean, responsive design for your blog:

theme:
  name: material
  palette:
    primary: indigo
    accent: indigo
  features:
    - navigation.tabs
    - navigation.top
    - search.suggest
    - search.highlight

Setting Up Blog Features

To turn your MkDocs site into a proper blog, add the blog plugin configuration:

plugins:
  - blog:
      blog_dir: blog
      post_date_format: yyyy-MM-dd
      post_url_format: "{date}/{slug}"
  - search
  - rss:
      match_path: blog/posts/.*
      date_from_meta:
        as_creation: date
      categories:
        - categories

Creating Blog Posts πŸ“°

Folder Structure

Create the following structure for your blog posts:

docs/
β”œβ”€β”€ blog/
β”‚   β”œβ”€β”€ posts/
β”‚   β”‚   β”œβ”€β”€ 2025-03-01-hello-world.md
β”‚   β”‚   └── 2025-03-09-setting-up-mkdocs.md
β”‚   └── index.md
└── index.md

Post Frontmatter

Each blog post should have frontmatter at the top, like this:

---
title: "Your Post Title"
date: 2025-03-09
authors:
  - yourname
description: "A brief description of your post."
categories:
  - Category1
  - Category2
tags:
  - tag1
  - tag2
---

# Your Post Title

Content goes here...

Adding Images and Media

To include images in your posts:

  1. Create an assets folder in your docs directory:
docs/
β”œβ”€β”€ assets/
β”‚   └── images/
β”‚       └── screenshot.png
  1. Reference the image in your Markdown:
![Screenshot of MkDocs site](../assets/images/screenshot.png)

Running MkDocs Locally πŸ–₯️

To preview your blog locally and check how it looks before publishing, run:

mkdocs serve

This will start a local web server. Open your browser and go to:

http://127.0.0.1:8000/

to view your blog. The server will automatically reload when you make changes to your files.

Deploying to GitHub Pages πŸš€

Initialize a Git Repository

First, navigate to your project folder and initialize a Git repository:

git init
git add .
git commit -m "Initial commit"

Create a GitHub Repository

  1. Go to GitHub and log in.
  2. Click the "+" button in the top-right and select "New repository".
  3. Enter a Repository name (e.g., my-blog).
  4. Choose Public or Private, based on your preference.
  5. DO NOT initialize with a README, .gitignore, or license (since we are pushing an existing project).
  6. Click "Create repository".

After creating the repository, copy the repository URL (e.g., https://github.com/yourusername/my-blog.git).

Now, link your local project to the GitHub repository:

git remote add origin https://github.com/yourusername/my-blog.git
git branch -M main
git push -u origin main

Deploy Your Blog to GitHub Pages

To publish your blog on GitHub Pages, run:

mkdocs gh-deploy

This command builds your MkDocs project and pushes the static files to the gh-pages branch of your repository.

Enable GitHub Pages in Repository Settings

  1. Go to your GitHub repository.
  2. Navigate to Settings > Pages.
  3. Under Branch, select gh-pages and click Save.
  4. Your site will be live at https://yourusername.github.io/my-blog/ (Note: It may take a few minutes for your site to appear live after deployment).

Enhancing Your Development Experience πŸ’»

For an easier development experience, I recommend using Visual Studio Code (VS Code). You can install it from code.visualstudio.com.

  • Python (for virtual environment support)
  • Markdown Preview Enhanced (for writing and previewing Markdown files)
  • YAML (for editing mkdocs.yml)
  • Material Theme Icons (for a nicer file tree visualization)

Troubleshooting Common Issues πŸ”§

Site Not Deploying

If your site isn't appearing after running mkdocs gh-deploy:

  • Check if you've configured GitHub Pages in your repository settings
  • Ensure you've pushed your changes to the correct branch
  • Wait a few minutes as GitHub Pages deployment can take time

Styling Issues

If your theme isn't applying correctly:

  • Verify the theme is installed (pip install mkdocs-material)
  • Check for syntax errors in your mkdocs.yml file
  • Try clearing your browser cache

Conclusion πŸŽ‰

Setting up MkDocs is straightforward, and with GitHub Pages, you can host your blog for free. The Material theme provides excellent styling out of the box, and with the right plugins, you can create a fully-featured blog with minimal effort.

In future posts, I'll cover more customizations, themes, and plugins to enhance your MkDocs blog. Stay tuned!


Share on Share on