wordpresswordpress-gutenberggutenberg-blockscreate-guten-blockgutenberg-reusable-block

How to set default alignment for core/buttons block to center in Gutenberg block development?


I'm developing a custom Gutenberg block where I am using the core/buttons block inside my custom block template. I want the buttons to be aligned to the center by default when the block is rendered, but I haven't found any straightforward way to do this using the align attribute or similar settings.

Here’s what I’ve tried:

Here’s part of my current code:

const CUSTOM_TEMPLATE = [
    [
        "core/heading",
        {
            placeholder: "Enter title here",
            textAlign: "center",
        },
    ],
    [
        "core/buttons",
        {
            className: "mrz-cta-button is-content-justification-center", // Hack to force center alignment
            align: "center", // Not working
        },
        [
            [
                "core/button",
                {
                    placeholder: "Click Now",
                    text: "Click Me",
                    align: "center", // Not working
                },
            ],
        ],
    ],
];

What I'm Looking For:

Any help or insights on how to handle this would be greatly appreciated!


Solution

  • The alignment of all child buttons within the Buttons block is controlled by the layout property, justifyContent: "center" of core/buttons. In your template, adjust it to be:

    const CUSTOM_TEMPLATE = [
            ...
            [
                "core/buttons",
                {
                    // nb. remove additional classes that replicate centering
                    layout:
                    {
                        type: "flex", // required
                        justifyContent: "center" // controls layout of child buttons
                    }
                },
                [
                    [
                        "core/button",
                        {
                            placeholder: "Click Now",
                            text: "Click Me",
                        },
                    ],
                ],
            ],
        ];
    

    Other justifyContent options are left, right and space-between (all related to flex box). If you want to find other properties to use in templates, the quickest method is to create the block in the Editor by using the UI controls then switch to code view to discover the properties.