Adding Custom CSS to WordPress
Method 1: Using functions.php (Recommended)
Add this code to your child theme's functions.php file to properly enqueue your custom styles:
function add_custom_styles() {
wp_enqueue_style('custom-styles', get_stylesheet_directory_uri() . '/css/custom-styles.css', array(), '1.0.0');
}
add_action('wp_enqueue_scripts', 'add_custom_styles');
Create a new file: /wp-content/themes/your-child-theme/css/custom-styles.css
and add your CSS there.
Method 2: Using wp_head Hook
Add custom CSS directly in your theme's functions.php file:
function add_inline_custom_styles() {
echo '<style>
/* Your custom CSS here */
.site-header {
background-color: #f5f5f5;
padding: 20px;
}
.entry-title {
color: #333;
font-size: 24px;
}
</style>';
}
add_action('wp_head', 'add_inline_custom_styles');
Method 3: Using wp_add_inline_style
Add custom CSS that depends on an existing stylesheet:
function add_dependent_custom_styles() {
$custom_css = "
.site-content { max-width: 1200px; }
.widget-area { background: #fafafa; }
";
wp_add_inline_style('twenty-twenty-one-style', $custom_css);
}
add_action('wp_enqueue_scripts', 'add_dependent_custom_styles');
Using WordPress Customizer API
Add a custom CSS section to the WordPress Customizer:
function custom_css_customizer($wp_customize) {
$wp_customize->add_section('custom_css_section', array(
'title' => 'Custom CSS',
'priority' => 200
));
$wp_customize->add_setting('custom_css_setting', array(
'default' => '',
'sanitize_callback' => 'wp_filter_nohtml_kses'
));
$wp_customize->add_control('custom_css_control', array(
'label' => 'Add Custom CSS',
'section' => 'custom_css_section',
'settings' => 'custom_css_setting',
'type' => 'textarea'
));
}
add_action('customize_register', 'custom_css_customizer');
function output_custom_css() {
$custom_css = get_theme_mod('custom_css_setting');
if (!empty($custom_css)) {
echo '<style>' . esc_html($custom_css) . '</style>';
}
}
add_action('wp_head', 'output_custom_css');
Plugin Solutions
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
-
Yellow Pencil - Visual CSS editor with live preview
Best Practices
- Always use a child theme for custom CSS
- Minimize inline styles
- Use proper CSS specificity
- Keep CSS organized and commented
- Use CSS preprocessors for larger projects
- Test styles across different devices and browsers
- Use WordPress debug mode while developing
Choose Method 1 for most cases as it:
- Properly enqueues stylesheets
- Maintains clean separation of concerns
- Allows for easy caching
- Follows WordPress best practices