CSS Hover Effect | Web Development

By Saheb Sutradhar - Updated On 29-04-2024

CSS Hover Effect | Web Development

In web development, user experience (UX) plays a crucial role. CSS hover effects are a powerful tool to enhance UX by adding subtle animations or visual changes when users hover their mouse over elements on your webpage. This blog post will guide you through creating a visually appealing and interactive image gallery using CSS hover effects.

HTML Structure:

<div class="container">
  <img src="1.png" alt="Image 1">
  <img src="2.png" alt="Image 2">
  <img src="3.png" alt="Image 3">
  <img src="4.png" alt="Image 4">
</div>

This code creates a container element (div) with the class "container" that holds four image elements (img) with their respective source paths and alt text for accessibility.

CSS Styling:

.container {
    display: flex; /* Makes the container a flex container */
    align-items: center; /* Aligns items vertically centered */
    justify-content: center; /* Aligns items horizontally centered */
    gap: 15px; /* Sets the gap between items inside the container */
}

img {
    width: 60px; /* Sets the width of the images to 60 pixels */
    height: 60px; /* Sets the height of the images to 60 pixels */
    cursor: pointer; /* Changes the cursor to a pointer when hovering over the images */
    transition: 1s; /* Adds a transition effect of 1 second to smooth the change */
}

.container:hover > :not(:hover) {
    transform: scale(0.3); /* Scales down all child elements of .container when .container is hovered, except the hovered element */
}

img:hover {
    transform: scale(1.6); /* Scales up the images to 1.6 times their original size when hovered */
    transition: 1s; /* Adds a transition effect of 1 second to smooth the change */
}

Understanding the CSS:

  • The .container class uses flexbox properties to horizontally and vertically center-align its child elements (the images).
  • The img class sets the dimensions of the images and changes the cursor to a pointer upon hover.
  • The .container:hover > :not(:hover) selector scales down all child elements of the container when the container itself is hovered, except for the currently hovered image.
  • The img:hover selector scales up the size of the image being hovered over, creating a visually appealing effect.

codelearningpoint © 2024