In this recipe, we created a child theme for the Twenty Twenty theme. However, no functionality is provided by the child theme at this stage. We can use a child theme to add custom styles and change the functionality of a parent theme. In this section, we are going to look at the process of adding custom styles with a child theme.
First, we have to add the necessary styles to the style.css file of our child theme inside the twentytwentychild folder. Let's use the following CSS to change the color of the theme header:
#site-header {
background: #21c7d8;
}
Now, you can check the home page of the site. At this stage, the style change we made is not visible on the site header. The reason for this is that we only included the parent theme's style.css file in the functions.php file of the child theme. First, remove the existing code in functions.php file. Then, include the child theme's style.css file along with the parent theme's CSS file by adding the following code to the functions.php file:
add_action( 'wp_enqueue_scripts', 'wpccp_chapter2_enqueue_parent_styles' );
function wpccp_chapter2_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style',
get_template_directory_uri().'/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' )
);
}
We already used the first wp_enqueue_style function to include the parent theme styles. The parent-style key can be changed to any unique name. The next line enqueues the child theme's style.css file with a dependency on parent theme styles. The get_template_directory_uri and get_stylesheet_directory_uri functions load the main theme directory and child theme directory paths. Now, you can visit the site and the changes in the header styles will be visible with the color we added.
If you aren't seeing the background color we added to the CSS file of the child theme, make sure to clear the browser cache and refresh the browser multiple times.
Before moving into the next recipe, remove or comment the CSS code added in the style.css file of the child theme.