Style Single Field Specific to a Content Type in Drupal 8

This article will guide you to change the style of a single field in a specific content type. Here I am going guide how to style 'Tags' field of 'article' content type. Standard Drupal 8 distribution comes with 'Article' content type, and it is having 'Tags' field. So, you can try out this on a standard Drupal 8 installation.

Here, the field's name is 'field_tags' and entity type and bundle where the field is attached are 'node' and 'article' respectively. Default template file for any field is 'field.html.twig'. You could copy it under your theme directory, but it will affect every field in your Drupal installation. There are provisions to make it specifically apply to a field of a single content type.

If you take function system_theme_suggestions_field() implementing hook_theme_suggestions_HOOK() in system module. You can see, it add several theme suggestions including suggestion of pattern field__<entity_type>__<field_name>__<bundle>. If you provide template file following this pattern in your theme, Drupal will give it precedence over 'field.html.twig' when field name, entity type and bundle are matched. To have template file following this pattern, we need to create template file of having name of this pattern but all underscores to be replaced with hyphens. So, it will become field--<entity_type>--<field_name>--<bundle>.html.twig. To make it specific for 'field_tags' of 'node' of 'article' bundle. The template file should be named as 'field--node--field-tags--article.html.twig'.

Once created 'field--node--field-tags--article.html.twig' file under your theme directory, copy content of 'field.html.twig' to it.

Now we need to apply CSS style changes to this field. For that we will define a library that will be attached when 'field_tags' of 'article' node get rendered. To define the library entry. Open 'MY_THEME.libraries.yml' and put these lines:

field--node--field-tags:
  version: VERSION
  css:
    theme:
      css/field--node--field-tags.css: {}

Here we defined a library entry 'field--node--field-tags' containing only one CSS file. Create the file 'css/field--node--field-tags.css' inside your theme then apply necessary styles you want.

We created a library item and created the CSS style. Now we need to load that library when our 'field_tags' rendered for article nodes. For that, open 'MY_THEME.theme' file and implement hook_preprocess_HOOK() for field templates and load library field--node--field-tags when conditions are satisfied.

/**
 * Implements hook_preprocess_HOOK() for field templates.
 */
function MY_THEME_preprocess_field(&$variables) {
  $element = &$variables['element'];
  if ($element['#field_name'] == 'field_tags'
      && $element['#entity_type'] == 'node'
      && $element['#bundle'] == 'article'
  ) {
    $variables['#attached']['library'][] = 'MY_THEME/field--node--field-tags';
  }
}

Clear the cache, we have done!