Creating a Drupal 8 sub-theme, or sub-theme of sub-theme

Last updated on
23 March 2017

Sub-themes are just like any other theme, with one difference: they inherit the parent theme's resources. There are no limits on the chaining capabilities connecting sub-themes to their parents. A sub-theme can be a child of another sub-theme, and it can be branched and organized however you see fit. This is what gives sub-themes great potential.

To create a sub-theme you define your theme like any other theme and declare the base theme using the "base theme" key. Note that the key has no underscore.

Example sub theme Fluffiness

This is an example of a sub-theme that uses Classy as a base theme. The info file is named fluffiness.info.yml.

name: Fluffiness
type: theme
description: This is a fluffy sub theme of Classy
core: 8.x
# Defines the base theme
base theme: classy
# Defines libraries group in which we can add css/js.
libraries:
  - fluffiness/global-styling
# Regions
regions:
  header: Header
  featured: Featured
  content: Content
  sidebar_first: First sidebar
  sidebar_second: Second sidebar
  footer: Footer

Include fluffiness.libraries.yml file to add css/js in `global-style` group (defined above in `libraries:` key).

global-styling:
  css:
    component:
      css/style.css: {}

Read more about adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

Sub-theme of sub-theme

In case you are creating sub-theme of sub-theme you have to mention your sub-theme you want to extend as base theme.

First sub-theme of Classy (Fluffiness):

name: Fluffiness
type: theme
description: This is a fluffy sub theme of Classy
core: 8.x
# Defines the base theme
base theme: classy

Next level sub-theme (of Fluffiness) shall have:

name: Shaved
type: theme
description: This is a reduced fluff sub theme of Fluffiness
core: 8.x
# Defines the base theme
base theme: fluffiness

Inheriting Block Templates

If the theme you are extending has custom block templates these won't be immediately inherited because a sub-theme creates copies of all the blocks in the parent theme and renames them with the sub-theme's name as a prefix. Twig block templates are derived from the block's name, so this breaks the link between these templates and their block. Fixing this problem currently requires a hook in the sub-theme.  Following the examples above we'd create a file called shaved.theme in the sub-theme's directory.  In that file insert this hook.

function shaved_theme_suggestions_block_alter(&$suggestions, $variables) {
  foreach ($suggestions as &$suggestion) {
    $suggestion = str_replace('shaved_', '', $suggestion);
  }
}

For your own sub-themes replace "shaved" with the name of your sub-theme.

Differences with Drupal 7

The most notable difference with Drupal 7 is that .info files have become .info.yml files that use the YAML syntax