I recently added a masonry-style layout to the default WordPress gallery block using just ~55 lines of PHP and CSS — no extra plugins required! All you need to do is click the gallery block and choose Masonry style. Once you add your gallery, I recommend clicking the Link icon and than selecting Enlarge on click option.




Here's why it's neat:
- It uses WordPress's built-in block style registration.
- The CSS only loads if the “Masonry” style is actually used.
- It works responsively out of the box.
If you're using a block theme (like GeneratePress), this is a clean way to enhance the core/gallery block.
Here's the code if you don't want to import the Snippet:
// Register the 'masonry' gallery block style
function register_masonry_gallery_block_style() {
register_block_style(
'core/gallery',
array(
'name' => 'masonry',
'label' => __( 'Masonry', 'generatepress' ),
)
);
}
add_action( 'init', 'register_masonry_gallery_block_style' );
// Conditionally enqueue CSS only if the 'masonry' gallery block style is present
function enqueue_masonry_gallery_styles() {
if ( is_singular() ) {
global $post;
if ( $post && has_block( 'core/gallery', $post ) ) {
$content = $post->post_content;
if ( strpos( $content, 'is-style-masonry' ) !== false ) {
$css = "
.is-style-masonry {
display: block !important;
-webkit-columns: 3;
-moz-columns: 3;
columns: 3;
column-gap: var(--wp--style--unstable-gallery-gap, 1rem);
}
@media (max-width: 1024px) {
.is-style-masonry {
columns: 2;
}
}
@media (max-width: 600px) {
.is-style-masonry {
columns: 1;
}
}
.is-style-masonry .wp-block-image {
width: 100% !important;
margin-bottom: var(--wp--style--unstable-gallery-gap, 1rem) !important;
display: inline-block;
break-inside: avoid;
}
";
wp_register_style( 'masonry-gallery-inline-style', false );
wp_enqueue_style( 'masonry-gallery-inline-style' );
wp_add_inline_style( 'masonry-gallery-inline-style', $css );
}
}
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_masonry_gallery_styles' );
Alternatives
- 3 kb – my code snippet solution above
- https://gutenberghub.com/how-to-create-a-masonry-gallery-in-wordpress/
- 59.1 kb https://wordpress.org/plugins/mgb-masonry-image-gallery/
- 721 kb https://wordpress.org/plugins/grid-masonry-for-guten-blocks/
- 953 kb – https://wordpress.org/plugins/gs-pinterest-portfolio/
- https://duckduckgo.com/?q=generateblock+gallery+image&ia=web