2

The design I am working with calls for each Gutenberg block to have a coloured background (white in this case) with max-width: 1160px and the content within to have max-width: 800px and centered. Similar to the image below:

enter image description here

Which would need a setup like this:

<main class="site-background">
    <div class="width-1160">
        <p class="width-800">Some text content...</p>
    </div>
</main>

At this time we are only using core Gutenberg blocks but the markup it produces is similar to the below, without the containing <div>:

<main class="site-background">
    <p class="width-800">Some text content...</p>
</main>

Is there a way to add a containing <div> to all Gutenberg content blocks that will be safe when core updates?

2

I'm sure there are other ways e.g. with CSS only or Add custom class to core blocks in Gutenberg, but regarding:

Add a containing DIV to core Gutenberg blocks

one way could be with the render_block filter:

add_filter( 'render_block', function( $block_content, $block ) {
    // Target core/* and core-embed/* blocks.
    if ( preg_match( '~^core/|core-embed/~', $block['blockName'] ) ) {
       $block_content = sprintf( '<div class="some__class">%s</div>', $block_content );
    }
    return $block_content;
}, PHP_INT_MAX - 1, 2 );

to div-wrap the core blocks on the frontend.

Changing the HTML layout might affect the current style of the site.

  • This seemed to do the trick. We have what appears to be a complicated layout that needs to work with Gutenberg where main blocks have a background-color but will have stand-out/feature quotes in-between content that will have a transparent background. It's the only solution I can think of at this time. – Bagseye Mar 1 at 12:39
  • Glad to hear it was somewhat helpful. – birgire Mar 1 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.