.wp-block-gallery.custom-masonry-gallery {
    display: block !important;
    position: relative;
    gap: 0 !important;
    opacity: 0; /* Initial fade state */
    transition: opacity 0.4s ease-in-out;
    /*
      KEY FOR CLS: Attempt to reserve vertical space.
      Adjust this value based on your typical gallery content.
      e.g., if you typically have 2 rows of images around 300px high = 600px + gaps.
    */
    min-height: 400px; /* !!! ADJUST THIS VALUE !!! */
}

.wp-block-gallery.custom-masonry-gallery.masonry-initialized {
    opacity: 1;
    min-height: 0; /* Once initialized, Masonry controls height, so min-height can be removed or set to 0/auto */
}

.wp-block-gallery.custom-masonry-gallery > figure.wp-block-image {
    margin-bottom: 10px !important; /* Vertical Gutter */
    box-sizing: border-box;
    flex-grow: 0 !important;
    flex-shrink: 0 !important;
    flex-basis: auto !important;
    margin-left: 0 !important;
    margin-right: 0 !important;
    display: block;
    padding: 0;
    visibility: hidden; /* Hide items initially, they will be positioned by Masonry */
    /* Width definitions are crucial for Masonry's columnWidth calculation */
}

/* When Masonry is initialized, items become visible in their correct positions */
.wp-block-gallery.custom-masonry-gallery.masonry-initialized > figure.wp-block-image {
    visibility: visible;
}


/* Responsive item widths */
/* Mobile-first: default to 2 columns */
.wp-block-gallery.custom-masonry-gallery > figure.wp-block-image {
    width: calc(50% - 5px); /* 2 columns, 10px gutter */
}

@media (min-width: 768px) {
    .wp-block-gallery.custom-masonry-gallery:not([class*="columns-"]) > figure.wp-block-image,
    .wp-block-gallery.custom-masonry-gallery.columns-default > figure.wp-block-image,
    .wp-block-gallery.custom-masonry-gallery.columns-3 > figure.wp-block-image {
        width: calc(33.333% - 6.67px); /* 3 columns */
    }

    .wp-block-gallery.custom-masonry-gallery.columns-2 > figure.wp-block-image {
        width: calc(50% - 5px); /* 2 columns */
    }

    .wp-block-gallery.custom-masonry-gallery.columns-4 > figure.wp-block-image {
        width: calc(25% - 7.5px); /* 4 columns */
    }
}

.wp-block-gallery.custom-masonry-gallery > figure.wp-block-image img {
    display: block;
    width: 100%;
    height: auto; /* Relies on width/height attributes on img tag for aspect ratio */
    max-width: 100%;
    margin: 0;
    padding: 0;
    vertical-align: bottom;
}

/* FsLightbox specific */
.wp-block-gallery.custom-masonry-gallery a[data-fslightbox] {
    cursor: pointer;
}