Make custom block full-width in Gutenberg by default

By default, all blocks are inserted with the same width in the Gutenberg editor. Depending on the block and theme support, you get the option to set blocks to wide or full width, to let the block go beyond the normal content width on the website.

Now I had the case that a custom block should be displayed full-width by default, without the option to change that. On the frontend, I just modified the styling, but in the editor, there are a few more adjustments necessary because the block controls for a full-width block are above the block, not on the left side.

Update from August 20, 2020: Fabian Kägy posted a code snippet in the comments that shows a way to make this also work for core or third-party blocks 🎉 I updated the second part of the post accordingly.

To recreate that behavior, I set the align attribute to full and add data-align="full" to the block wrapper. That is done by the following code in the registerBlockType() object:

attributes: { align: { type: 'string', default: 'full', } }, getEditWrapperProps() { return { 'data-align': 'full', }; },

Of course, that only works for own blocks that you created (the alignfull class name is not added automatically here).

To get the same behavior for core or third-party blocks, where we cannot modify the registerBlockType() object, we can use the blocks.registerBlockType filter, like in the following code example:

const modifyDefaultAlignment = ( settings, name ) => { if ( name !== 'core/media-text' ) { return settings; } const newSettings = { ...settings, attributes: { ...settings.attributes, align: { type: 'string', default: 'full' }, }, }; return newSettings; }; wp.hooks.addFilter( 'blocks.registerBlockType', 'textdomain/change-media-text-default-alignment', modifyDefaultAlignment, );

The code checks for the core/media-text block and, if we have one, adds the align attribute to the settings with full as the default value. That works only if the theme has support for wide and full alignment enabled.

3 thoughts on »Make custom block full-width in Gutenberg by default«

  1. Hi Florian,

    Thats cool 🙂 I never thought about doing it that way!

    The way I always modify the default alignment of any block is by using this hook:

    import { addFilter } from '@wordpress/hooks';
    const modifyDefaultAlignment = (settings, name) => {
    	if (name !== 'core/media-text') {
    		return settings;
    	}
    	const newSettings = {
    		...settings,
    		attributes: {
    			...settings.attributes,
    			align: { type: 'string', default: 'full' },
    		},
    	};
    	return newSettings;
    };
    addFilter(
    	'blocks.registerBlockType',
    	'textdomain/change-media-text-default-alignment',
    	modifyDefaultAlignment,
    );
    

Leave a Reply

Your email address will not be published. Required fields are marked *