Material for Mkdocs 9.5 – new in the release and useful hacks when working with documentation

Material for MkDocs my favorite engine for building documentation and the HOSTKEY documentation is built on it.

In December 23, Material for MkDocs was updated to version 9.5, but due to regressions they did not dare to switch to it (and, judging by the changes, it was not worth it a month ago). But now the version is already quite stable and corrected, so you can decide to move to the 9.5.x branch. At the time of writing this text, the release version is 9.5.13.

We are updating

I recommend always installing a specific version, not the latest one, and checking all updates on the test server. To do this we use the command:

pip install mkdocs-material=="version" to install, and pip install update mkdocs-material==”version” to update. In our case, version will be 9.5.13.

But if you are on branch 9.4 or younger, then update via standard pip install won't happen since 9.5 will be the next major version. Therefore we use the command

pip install --upgrade --force-reinstall mkdocs-material=="version"

What's new in version 9.5

In this version, several functions that were previously available only for money to project sponsors were transferred to free access. Some of them are already enabled by default, some need to be specified in the configuration file mkdocs.yml on one's own.

  • Privacy plugin. When assembling documentation, all external assets (scripts, etc.) are downloaded and saved locally. A useful feature so that your statically collected documentation does not fall ill due to problems with an external resource.

  • Document contributors And Document Authors. Allows you to display an avatar and the name of all contributors to a given page or just its author at the bottom of the document. The information is taken from your GIT project.

  • Improved tooltips. You can now add small tooltips to titles, links, anchors and icons. I personally couldn’t figure out where this could be used, and this function worked crookedly for me, displaying a tooltip to the side of the link.

  • Сontent tabs anchor links. Anchor links for tabs are now automatically created, allowing you to create transitions to specific tabs in your text. This function is useful and allows you to link directly to the desired one when formatting text, for example, for different operating systems or methods.

I have already used the following new functions in the documentation, and therefore I will tell you about them in more detail.

Automatic dark/light theme

Previously, also in Material fo Mkdocs, you could add a switch between a light or dark theme to a page, but now there is an automatic option that sets the theme depending on your system settings. Here you can rely on the default settings, but if you want to do it “like ours”, then this is the code you need to add to stylesheets/extra.css your documentation (and don't forget to specify the use of this CSS file in mkdocs.yml):

/* Настройка цветов для светлой и темной тем */

[data-md-color-scheme=default] {
  --md-default-fg-color--light: 000;
  --md-primary-fg-color: #ff6e42;
}

[data-md-color-scheme=slate] {
  --md-default-fg-color--light: hsla(var(--md-hue), 15%, 100%, 0.8);
  --md-primary-fg-color: #121215;
}

Here we set the foreground color to black for the main elements (headers, etc.) for the light theme (which is default), and for the dark theme (slate) we change it by changing the brightness. We will also use these values ​​later to change specific elements, in our case buttons, to suit the theme we need.

Generic Grid

This new feature allows you to arrange custom block elements in a grid, including ads, code blocks, content tabs, and more. Now in your documentation you can do things like this (more precisely, you could do them before, but using html code in Markdown files). You just need to “wrap” everything in <div class="grid" markdown> ... </div>.

Let's warn you right away – do not use generic grid with drop-down ads, as this will lead to an error in rendering the text behind the grid.

Card grid

A grid of cards allows you to beautifully design the main or index pages of documentation. Previously, it was available only in the sponsor (insiders) thread, but now it is available to everyone.

What happened before? To design the main page, it was possible to use a table (which is what I did when developing the documentation), but then two questions arose: Material for Mkdocs, by default, sets the width of the columns according to the content and this entire structure (in my case, three columns) moved apart when viewed in mobile version.

Since Mkdocs allows you to add HTML and CSS directly to the text of the article, the first one was corrected with the following code:

<style type="text/css">
  .md-typeset__table {
        table { width: 100%; }
        th, td { width: 33.33%; }
    }
</style>

This CSS code causes three equal-width columns to appear on a page, and you can apply it to the pages you want by simply placing it at the end of the article (and adjusting the values).

To prevent our table (or rather, three tables of two rows and three columns) from collapsing in the mobile version, the following CSS code was added:

<style type="text/css">

@media screen and (max-width: 800px) {
.md-typeset__table {
    table { width: 100%; }
    th { display: inline-block; }
    th { font-size: 0.8rem; }
    td { display: none; }
    th { width: 100%; }
    td { with: 0%; }
	}
}

</style>

This code allows you to move columns and leave only the headings in them, removing the description text when moving to a mobile layout.

But with the advent Card Grid everything has become a little simpler (and I think prettier). You enclose all the cards in a block <div class="grid cards" markdown></div>. The syntax for a single card will look like this (a card with an icon, a title with a link, a description and a “More details” link):

<div class="grid cards" markdown>

- [:fontawesome-solid-gamepad:{ .lg .middle } **Панель управления INVAPI**](./controlpanel/index.md)

    ---

    Панель управления услугами: новые заказы, управление сервером

    [:octicons-arrow-right-24: Подробнее](./controlpanel/index.md)

</div>

By default, if you have the right and left navigation menus enabled, it displays two cards in a row, the text is aligned to the left, and in the mobile version the cards are next to each other.

But if you want 3 cards in a row with text in the center or want to remove the “More details” line from the mobile version, then CSS comes to our rescue again. We place the following code at the end of the page with our cards:

<style type="text/css">

/* делаем ширину карточек меньше, чтобы влезало  в три карточки в ряд на HD+ разрашениях */

.md-typeset .grid {
    grid-gap: 0.4rem;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(100%, 12rem), 1fr));
    margin: 1em 0;
}

/* отображаем содержимое по центру */

.md-typeset ul li p {
    text-align: center;
}

/* В мобильной версии отображаем что влазит + убираем ссылку Подробнее" */

@media screen and (max-width: 800px) {
.md-typeset .grid {
    grid-template-columns: repeat(auto-fill, minmax(min(100%, 16rem), 1fr));
}

.md-typeset p:not(:first-child) {
    display: none;
}

.md-typeset p:not(:last-child) {
    display: block;
}

}

</style>

The following things also work on previous versions of Material for Mkdocs, but I think they will also be useful to those who decide to create documentation on it.

Beautiful buttons and light/dark theme

There is initially no “Button” design element in Material for Mkdocs (more precisely, there is, but only for keyboard keys). So I used a modification of the strikethrough style (del). But in order for the buttons to display correctly in both light and dark themes, I had to tinker a little. More precisely, add the following code to extra.css:

/* применяем вместо кнопки элемент del (~~текст~~) */

del {

  text-decoration: none;
  background-color: var(--md-primary-fg-color);
  color: var(--md-default-fg-color--light);
  padding: 4px 4px;
  border: solid var(--md-default-fg-color--light) 1px;
  white-space: nowrap;
  border-radius: 5pt;

}

As you can see, we use variable colors for the elements that are used in the light or dark theme. As a result, when you change the theme, the color design of the buttons also changes:

TOC in mobile version

Another modification (more precisely, a life hack) was the addition of mini-content from second-level headings to the text of the article at the beginning. Here we had to solve two problems: by default in Mkdocs Material slag does not work properly to create anchors with characters other than Latin, and such a setting/element does not exist in the engine.

The first problem is solved by adding the following lines to the mkdocs.yml configuration file:

markdown_extensions:

  - toc:
      permalink: true
      slugify: !!python/object/apply:pymdownx.slugs.slugify

After this, autocompletion begins to work correctly for you (including in the VS Code view editor) even after assembling the anchor link of the #Russian text type. It is enough to put a link or image design. Moreover, this works both on the current page and throughout the entire documentation tree.

To solve the second problem, since not all users are able to get to the page content in the mobile version (and not in the mobile version either), it was decided to add a mini-content “In this article”, as was done, for example, in the Microsoft documentation. To do this, we used a standard quote, slightly “tuning” it with CSS code.

At the beginning of the article, it is now enough to place (after the first-level page heading) the following code, where we list links to second-level headings:

> **В этой статье**

> - [Порядок использования панели](#порядок-использования-панели)

> - [Описание контрольной панели сервера](#описание-контрольной-панели-сервера)

---

And we format the display of this text using this CSS code in extra.css, reducing the text size and removing list icons.

/* Убираем у цитаты значки списков, чтобы сделать мини TOC *

  .md-typeset blockquote {
    font-size: 0.65rem;
    ul { list-style-type: none;}
  }

The result we get is the following (in desktop and mobile versions):

If you are interested in other questions regarding MkDocs for Material, write in the comments. I will be glad to analyze the settings and share tricks and hidden ways to use it.

And you can see how everything looks “live” directly in the collected documentation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *