Skip to content

Snippet: How to Load a Custom CSS File for Mobile Only

When using the default header (not the header builder), the theme provides a Mobile Menu Breakpoint option. This controls when the theme switches from the standard menu to the mobile menu and also triggers layout changes like converting a vertical header to a horizontal one or hiding specific elements.

If you want to add custom CSS that respects this breakpoint, you can't rely on CSS variables since they're not supported for this purpose. Instead, you can either:

  1. Load your own CSS file through your child theme using the same media query the theme uses for the breakpoint, or
  2. Add inline CSS with the appropriate media query.
// Option 1: Load a custom CSS file for mobile only using the mobile menu breakpoint.
add_action( 'wp_enqueue_scripts', function () {
    $parent_handle = 'wpex-mobile-menu-breakpoint-max';

    // Return early if the target style isn't registered
    if ( ! wp_style_is( $parent_handle, 'registered' ) ) {
        return;
    }

    // Get the global styles object
    $styles = wp_styles();

    // Get the media query value from the registered style
    $media = $styles->registered[ $parent_handle ]->args;

    // Path to the child theme CSS file
    $relative_path = '/css/responsive.css';
    $file_path     = get_stylesheet_directory() . $relative_path;
    $file_uri      = get_stylesheet_directory_uri() . $relative_path;

    // Get file modification time for cache-busting
    $version = file_exists( $file_path ) ? filemtime( $file_path ) : null;

    // Enqueue the child theme stylesheet
    wp_enqueue_style( 'wpex-child-mobile-menu-breakpoint-max', $file_uri, [ $parent_handle ], $version, $media );
}, 20 );

// Option 2: Insert custom CSS inline on the site based on the mobile menu breakpoint media query.
add_action( 'wp_enqueue_scripts', function () {
    $handle = 'wpex-mobile-menu-breakpoint-max';

    // Return early if the style isn't registered
    if ( ! wp_style_is( $handle, 'registered' ) ) {
        return;
    }

    $styles = wp_styles();
    $media = $styles->registered[ $handle ]->args;

    // Your custom CSS to inject
    $custom_css = "
        /* Change body background */
        .body {
            background: blue;
        }
    ";

    // Wrap the CSS in the media query if it exists and isn't 'all'
    if ( $media && 'all' !== strtolower( $media ) ) {
        $custom_css = "@media {$media} { {$custom_css} }";
    }

    // Add inline style attached to the parent style handle (or any handle)
    wp_add_inline_style( $handle, $custom_css );

}, 20 );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top