Method 1: Using functions.php
Add custom CSS by enqueueing a stylesheet through your child theme's functions.php file:
Create a custom CSS file and enqueue it properly:
function add_custom_styles() {
wp_enqueue_style('custom-styles', get_stylesheet_directory_uri() . '/css/custom.css');
}
add_action('wp_enqueue_scripts', 'add_custom_styles');
Place this code in your child theme's functions.php file and create a /css/custom.css file in your child theme directory.
Method 2: Using wp_head Hook
Add CSS directly to the header using WordPress hooks:
function add_inline_styles() {
echo '<style>
/* Your CSS rules here */
.your-class {
color: #333;
background: #fff;
}
</style>';
}
add_action('wp_head', 'add_inline_styles');
Place this code in your child theme's functions.php file.
Method 3: Using wp_add_inline_style
Add CSS that depends on an existing stylesheet:
function add_dependent_styles() {
wp_register_style('parent-style', get_template_directory_uri() . '/style.css');
wp_enqueue_style('parent-style');
$custom_css = "
.your-class {
color: #333;
background: #fff;
}
";
wp_add_inline_style('parent-style', $custom_css);
}
add_action('wp_enqueue_scripts', 'add_dependent_styles');
Place this code in your child theme's functions.php file.
Method 4: Using Customizer API
Add CSS through WordPress Customizer:
function add_customizer_css() {
$custom_css = get_theme_mod('custom_css');
if ($custom_css) {
echo '<style>' . wp_strip_all_tags($custom_css) . '</style>';
}
}
add_action('wp_head', 'add_customizer_css');
function add_customizer_section($wp_customize) {
$wp_customize->add_section('custom_css_section', array(
'title' => 'Custom CSS',
'priority' => 200,
));
$wp_customize->add_setting('custom_css', array(
'default' => '',
'sanitize_callback' => 'wp_strip_all_tags'
));
$wp_customize->add_control('custom_css', array(
'label' => 'Custom CSS',
'section' => 'custom_css_section',
'type' => 'textarea',
));
}
add_action('customize_register', 'add_customizer_section');
Place this code in your child theme's functions.php file.
Plugin Alternatives
If you prefer using plugins, here are reliable options:
-
Simple Custom CSS - Lightweight solution for adding custom CSS
-
Custom CSS Pro - Advanced CSS editor with syntax highlighting
-
SiteOrigin CSS - Visual CSS editor with live preview
Best Practices
- Always use a child theme when adding custom code
- Minify CSS for production
- Use specific selectors to avoid conflicts
- Test CSS changes across different devices and browsers
- Back up your files before making changes