Mike Cho Development

Add CSS class to a content type: article in Drupal

You can do this by modifying the twig template that governs nodes–node-html-twig. Copy that over to your templates/content directory in your theme or sub-theme (make one if you don’t have one).

What follows is one of the simplest things you’ll have to deal with in theming, I think–which does not mean it’s as easy as you might hope.

The basic way the template works is it adds classes to the <article> by first creating an array that will store them, classes, and then adding that variable to the article using addClass. We are going to piggyback on this process by using the function merge.

Merge allows us to merge two arrays together. Unfortunately, there seems to be no easy way to just push a value to the array.

So, my particular node.html.twig uses the following classes:

set classes = [
'node--type-' ~ node.bundle|clean_class,
node.isPromoted() ? 'node--promoted',
node.isSticky() ? 'node--sticky',
not node.isPublished() ? 'node--unpublished',
view_mode ? 'node--view-mode-' ~ view_mode|clean_class,

Luckily, we don’t have to know what any of that means! Suffice it to say that it is the logic that ends up with outputting the appropriate classes to the article.

In our case, we want to add to the resulting array, using a simple control statement and then by merging a new array into the classes array.

That’s accomplished like this:

{% if node.bundle == 'article' %}
{% set classes = classes|merge(['my-class']) %}
{% endif %}

Now if you save and flush the cache, you’ll see the new class popping up in the article!