Create CSS Gallery Animations: 5 Easy Steps to Smooth View Transitions and Interactive Design – Full Source Code and Explanations

Introduction:

Creating eye-catching galleries with interactive animations and smooth transitions can make your website much more engaging and enjoyable for visitors. Whether you’re working on an online portfolio, an image gallery, or showcasing products, CSS gallery animations can greatly enhance your site’s appeal.

In this guide, we will walk you through five simple steps that will teach you the key techniques needed to add these seamless animations and transitions. This will help you achieve a visually stunning and responsive design.

By the end of this tutorial, you will have access to the full source code along with detailed explanations, enabling you to easily customize your own animated galleries. Get ready to learn how to master CSS animations and make your gallery elements come alive!

Step1: HTML For CSS Gallery Animations

HTML Code

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script type="module" src="main.js"></script>
    <title>Gallery with View Transitions | Blue_coderz</title>
    <link rel="shortcut icon" href="./final upscale.png" type="image/x-icon">
</head>
<body>
    <fieldset id="gallery" class="hub">
        <div>
          <input type="radio" id="image-1" name="gallery" value="image-1" checked>
          <img src="https://assets.codepen.io/2585/image_fx_a_black_wolf_in_armor_wrecking_a_steampunk_ci.jpg" alt="" />
          <label for="image-1">Cyber Wolf</label>
        </div>
      
        <div>
          <input type="radio" id="image-2" name="gallery" value="image-2">
          <img src="https://assets.codepen.io/2585/image_fx_cyberpunk_city_scene_with_neon_streaks_of_lig+%283%29.jpg" alt="" />
          <label for="image-2">Flying cars</label>
        </div>
      
        <div>
          <input type="radio" id="image-3" name="gallery" value="image-3">
          <img src="https://assets.codepen.io/2585/image_fx_cyberpunk_city_scene_with_neon_streaks_of_lig+%282%29.jpg" alt="" />
          <label for="image-3">Flying cars 2</label>
        </div>
        
        <div>
          <input type="radio" id="image-4" name="gallery" value="image-4">
          <img src="https://assets.codepen.io/2585/image_fx_cyberpunk_city_scene_with_neon_streaks_of_lig+%281%29.jpg" alt="" />
          <label for="image-4">Flying cars 3</label>
        </div>
         
        <div>
          <input type="radio" id="image-5" name="gallery" value="image-5">
          <img src="https://assets.codepen.io/2585/image_fx_cyberpunk_city_scene_with_neon_streaks_of_lig+%284%29.jpg" alt="" />
          <label for="image-5">Cyber T-Rex</label>
        </div>
         
        <div>
          <input type="radio" id="image-6" name="gallery" value="image-6">
          <img src="https://assets.codepen.io/2585/image_fx_a_raptor_in_armor_wrecking_a_cyberbunk_city_w.jpg" alt="" />
          <label for="image-6">Cyber Raptor</label>
        </div>
         
        <div>
          <input type="radio" id="image-7" name="gallery" value="image-7">
          <img src="https://assets.codepen.io/2585/image_fx_cyberpunk_city_scene_with_neon_streaks_of_lig.jpg" alt="" />
          <label for="image-7">Cyber freeway</label>
        </div>
      </fieldset>
      
</body>
</html>

HTML Explanation:

The HTML code provides the foundational structure for your gallery, ensuring all elements are properly organized. Key components include:

Document Declaration:

htmlCopy code<!DOCTYPE html>

This tells the browser that the document is an HTML5 document, crucial for correct rendering.

HTML Structure:

htmlCopy code<html lang="en">

This tag wraps the entire document, with the lang attribute indicating the language for better accessibility and SEO.

Head Section:

htmlCopy code<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive CSS Gallery</title>
    <link rel="stylesheet" href="style.css">
    <script type="module" src="main.js"></script>
</head>

This section includes metadata and links to external stylesheets and scripts. Notable elements are:

  • Character Encoding: Ensures the document supports special characters.
  • Viewport Settings: Adapts the layout for different screen sizes.
  • Stylesheet Link: Connects the external CSS file for styling.
  • Script Import: Loads the JavaScript file that adds interactivity.

Body Section:

htmlCopy code<body>
    <fieldset id="gallery" class="hub">
        <legend>Gallery</legend>
        <!-- Image inputs and descriptions -->
    </fieldset>
</body>

This section contains the visual elements, structured as follows:

  • Fieldset and Legend: Groups related elements and provides a caption.
  • Input Elements: Each radio input allows for image selection, ensuring only one can be chosen at a time.
  • Image and Description: Each image is linked to its input, and descriptions accompany the images.

Step 2 : CSS For CSS Gallery Animations

CSS Code

CSS
@import "https://unpkg.com/open-props/easings.min.css";
*{
  background-color: rgb(54, 54, 66);
}
@layer demo.view-transition {
  ::view-transition-group(*) {
    animation-duration: .5s;
    animation-timing-function: var(--ease-5);
  }

  .hub > * {
    @media (prefers-reduced-motion: no-preference) {
      /* Correcting the CSS selector */
      :nth-child(1) {
        view-transition-name: gallery-item-1;
      }
      :nth-child(2) {
        view-transition-name: gallery-item-2;
      }
      :nth-child(3) {
        view-transition-name: gallery-item-3;
      }
      :nth-child(4) {
        view-transition-name: gallery-item-4;
      }
      :nth-child(5) {
        view-transition-name: gallery-item-5;
      }
      :nth-child(6) {
        view-transition-name: gallery-item-6;
      }
      :nth-child(7) {
        view-transition-name: gallery-item-7;
      }
    }
  }
}

@layer demo.layout {
  .hub {
    display: grid;
    gap: 1rem;
    grid-template-columns: repeat(5, 15vw);
    grid-template-rows: repeat(3, 15vw);
    
    &.portrait {
      grid-template-columns: repeat(3, 20vw);
      grid-template-rows: repeat(5, 20vw);
    }

    /* Correcting pseudo-class syntax */
    > *:has(:checked) {
      grid-column: 1 / 4;
      grid-row: 1 / 4;
    }

    > * {
      display: grid;

      > * {
        grid-area: 1 / 1;
      }

      > label {
        opacity: 0;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;
      }

      > input {
        border-radius: 0;
        outline-offset: 5px;
        outline-color: deeppink;
        outline-color: color(display-p3 1 0 1);
      }
    }
  }
}

@layer demo.support {
  * {
    box-sizing: border-box;
    margin: 0;
  }

  html {
    block-size: 100%;
    color-scheme: dark light;
  }

  body {
    min-block-size: 100%;
    font-family: system-ui, sans-serif;

    display: grid;
    place-content: center;
  }

  fieldset {
    border: none;
    padding: 0;
    margin: 0;
  }

  img {
    max-inline-size: 100%;
  }

  /* Ensure view-transition is disabled for html */
  html {
    view-transition-name: none;
  }
}

CSS Explanation:

Global Styles:

cssCopy code* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    background-color: #121212;
    color: #ffffff;
}

This universal style applies to all elements, resetting margins and paddings, and setting a dark background.

Grid Layout:

cssCopy code.hub {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
}

The .hub class creates a responsive grid layout, allowing for flexible column sizes based on available space.

Image Styles:

cssCopy codeimg {
    width: 100%;
    border-radius: 10px;
    transition: transform 0.3s ease;
}
img:hover {
    transform: scale(1.05);
}

Images are set to fill their containers with a smooth scaling effect on hover.

Animation Effects:

cssCopy code@layer demo.view-transition {
    #gallery {
        view-transition-name: gallery;
        view-transition-duration: 0.5s;
        view-transition-easing: ease-in-out;
    }
}

This code applies view transitions to the gallery, enhancing visual effects during state changes.

Responsive Design:

cssCopy code@media (prefers-reduced-motion: no-preference) {
    img {
        transition: transform 0.3s ease;
    }
}

JavaScript Code

JavaScript

document.querySelectorAll('#gallery input').forEach(radio => {
    radio.onclick = e => {
      if (!document.startViewTransition) return
      
      e.preventDefault()
      
      function mutate() {

        e.target.checked = true

        e.target.parentNode.style.zIndex = null
      }
      

      e.target.parentNode.style.zIndex = 2
      
      document.startViewTransition
        ? document.startViewTransition(() => mutate())
        : mutate()
    }
  })
  

  function flipGallery() {
    function mutate(vertical = false) {
      if (document.startViewTransition)
        document.startViewTransition(() =>
          vertical
            ? gallery.classList.add('portrait')
            : gallery.classList.remove('portrait'))
    }
    
    mutate(window.innerWidth <= 768)
  }
  
  window.onresize = () => {
    clearTimeout(window.resizeEndTimer)
    window.resizeEndTimer = setTimeout(flipGallery, 100)
  }

JavaScirpt Explanation:

Event Listeners:

javascriptCopy codedocument.querySelectorAll('input[type="radio"]').forEach(input => {
    input.addEventListener('click', function() {
        // Animation logic
    });
});

This code attaches click events to each radio input, triggering associated animations.

View Transition Handling:

javascriptCopy codedocument.startViewTransition(() => {
    // Update the gallery based on the selected image
});

This method initiates transitions when an image is selected.

Dynamic Z-Index Adjustment:

javascriptCopy codefunction mutate() {
    const selectedInput = document.querySelector('input[type="radio"]:checked');
    selectedInput.parentNode.style.zIndex = '10';
    // Reset other z-index values
}

The mutate function modifies the z-index of the selected image to enhance focus during transitions.

Responsive Adjustments:

javascriptCopy codefunction flipGallery() {
    const width = window.innerWidth;
    if (width < 600) {
        // Adjust styles for smaller screens
    }
}

This function checks the window width and makes layout adjustments for better usability on smaller screens.

Live Preview the hosted website:

Download complete code :

CSS Gallery Animations

Git Hub link :

CSS Gallery Animations

Also Read Our Recent Animated Login Page:

signup page

Leave a Comment