Custom CSS per page or article with pelican

Published:

Updated:

By jeffmackinnon

For a little while now I have been trying to make my reading page look "prettier".

The main thing that I wanted was a really easy way to show if a book was a work in progress, finished or Did-not-finish. The page that I have been basing it on is this one. While I don't have the CSS/Python?RST skills to make it this pretty without a overhaul of the theme, I still wanted an easier way.

I tried a few things I found in my searches, the closest being this from duncanlock.net, but it kept breaking my page.

But it did lead me to an inspiration that made something work for me.

Adding some metadata to the page and a new custom library.css. So this is my solution, which may help you.

My solution

First I needed to add a new block to the base.html

{% block somemorehead %}
{% endblock somemorehead %}

I put this right after the existing {% block head %}.

Then I added this to page.html (I will go back to add something similar to article.html)

{% block somemorehead %}
    {% if page.specialcss %}
    <link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/{{ page.specialcss }}">
    {% endif %}
{% endblock somemorehead %}

This links to a new library css when the library css tag is true.

In library.css I have two classes:

.wip {
    width: 150px;
    opacity: 75%;
    border: 5px solid #d11586
}
.read {
    width: 150px;
}
.dnf {
    width: 150px;
    opacity: 75%;
    filter: grayscale(100%);
}

Finally I added :specialcss: library.css to the head of my reading.rst page file.

Now, when I add a class to the image, it will use this to make it look the way that I want.

1
2
3
4
.. image:: {static}/images/books/2022/IronDruid-Trapped.jpg
    :class: wip
    :width: 150px
    :alt: The Iron Druid Chronicles - Trapped

And that's it.

My Next Steps

If I start to use this a lot, I make customize it such that the meta data is something like :customcss: library.css and then that is the link on the page. This would allow me to have a bunch of little CSS snipets for specific pages. It will also help make my theme easier to extend to a bunch of different sites.

I will leave that troubleshooting and such to another day.

Edited: I came up with a "better" way to handle this that will allow me to have any page with its own .css if I wanted.

This post is part 4 of the "How I Pelican" series:

  1. Installing Pelican for the first time again
  2. I updated a theme
  3. EXIF data with a pelican-photos Gallery
  4. Custom CSS per page or article with pelican
  5. Batch Files are your friend