Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Understanding Sub-Themes in Drupal

What is a Sub-Theme?

A sub-theme in Drupal is a theme that inherits its properties and functionality from a parent theme. It allows developers to customize and extend a parent theme without modifying the original theme files. This is useful for maintaining updates and ensuring that customizations are preserved when the parent theme is updated.

Why Use Sub-Themes?

Using sub-themes provides several benefits:

  • Maintainability: Changes can be made in the sub-theme without affecting the parent theme.
  • Flexibility: Allows for extensive customization while inheriting base styles and functionality.
  • Consistency: Helps maintain a consistent design across multiple projects by using a common parent theme.

How to Create a Sub-Theme

Creating a sub-theme in Drupal involves several steps:

  1. Select a Parent Theme: Choose a base theme that you want to extend.
  2. Create a Sub-Theme Directory: In your Drupal installation, navigate to the themes/custom directory and create a new folder for your sub-theme.
  3. Create a .info.yml File: Create a `.info.yml` file in the new sub-theme directory. This file contains metadata about your theme.
  4. Override Styles and Templates: Add custom CSS or override template files as needed.
  5. Enable the Sub-Theme: Use the Drupal admin interface or Drush to enable your new sub-theme.

Example of Creating a Sub-Theme

Let's walk through creating a sub-theme named "my_subtheme" based on the "Bartik" theme.

Step 1: Create the Directory

Create a directory named my_subtheme in themes/custom/.

Step 2: Create the .info.yml File

Create a file named my_subtheme.info.yml with the following content:

name: My Sub-Theme
type: theme
base theme: bartik
description: 'A sub-theme based on Bartik.'
region: header:
region: content:
region: footer:

Step 3: Enable the Sub-Theme

Use the following Drush command to enable the sub-theme:

drush theme:enable my_subtheme

Step 4: Customizing Styles

You can create a css folder in your sub-theme directory and add a file named styles.css. Include it in your .info.yml file:

libraries:
- my_subtheme/global-styling

And create a my_subtheme.libraries.yml file:

global-styling:
css:
theme:
- css/styles.css

Conclusion

Sub-themes in Drupal are a powerful way to customize and extend parent themes while keeping your modifications organized and maintainable. By following the steps outlined in this tutorial, you can create your own sub-theme and start customizing your Drupal site effectively.