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:
Using the align
attribute and setting it to center
, but it doesn’t seem to work with the core/buttons
block.
I tried using the className
property to add the is-content-justification-center
class as a hack,but this approach has some issues. Specifically, even when I set the alignment to left, the button remains centered because of the hardcoded class. In order to properly move the button to the left, I have to first click on center or right alignment and then click left. Here's a screenshot of the issue: https://prnt.sc/vZ0yKfZ7XJah.
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:
Is there a clean, recommended way to set the default alignment of the core/buttons block to center?
Can this be achieved using attributes or a more appropriate approach rather than relying on adding classes manually?
Any help or insights on how to handle this would be greatly appreciated!
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.