Back to Community

How to Modify the Default CSS Class of Your Custom Gutenberg Block

37 threads Sep 16, 2025 CoreDeveloping with wordpress

Content

When you create a custom Gutenberg block using the official create-block tool, WordPress automatically wraps your block's content in a default CSS class. This class follows the pattern .wp-block-create-block-{your-block-name}. While this is useful for basic styling, many developers want to customize this class for better semantics, consistency with their theme, or to follow a specific naming convention.

Why Change the Default Class?

The automatically generated class name is functional but not always ideal. You might want to change it to:

  • Match your theme's existing class naming structure (e.g., BEM methodology).
  • Create a shorter, more readable class name.
  • Ensure consistency across multiple custom blocks.

The Solution: Using the useBlockProps Hook

You can easily define a custom wrapper with your own class names by modifying the save function in your block's JavaScript file. The key is to use the useBlockProps.save() function provided by the @wordpress/block-editor package.

Here is a code snippet demonstrating how to implement this:

// Import the necessary hook
import { useBlockProps } from '@wordpress/block-editor';

// Inside your save function
export default function save() {
    // Use useBlockProps.save() to define a custom className
    return (
        <div {...useBlockProps.save({ className: 'my-custom-class' })}>
            <p>Your block content goes here...</p>
        </div>
    );
}

How It Works

  • useBlockProps.save(): This React hook is essential for handling the block's wrapper props during the save phase. It generates the necessary data attributes and classes WordPress needs to manage the block.
  • className property: By passing an object with a className property to the hook, you can append your own custom class to the wrapper element. WordPress will still add its own classes for identification, but your custom class will be included.

Important Considerations

  • Preservation of Core Classes: This method adds your custom class alongside WordPress's core classes. It does not remove the default classes, which are required for the block editor to function correctly.
  • Block Validation: Changing the output of the save function can sometimes cause block validation errors if an existing block on a page was saved with the previous markup. Be mindful of this when updating blocks on a live site.
  • Additional Props: The useBlockProps hook handles more than just classes; it also manages other attributes like alignment and typography settings defined in your block.json. Using this hook ensures you don't lose that functionality.

By following this approach, you gain full control over the HTML output of your custom Gutenberg blocks, allowing for cleaner code and more maintainable styling.

Related Support Threads Support