Initializing the project
Let's start the project by creating a Next.js application. We can do that by running npx create-next-app@13.2.4 myApp
inside of a terminal.
Adding the HTML and CSS
We can delete everything in the index.js
and add our own HTML and CSS.
For the CSS, we're going to use CSS Module, so make sure to create a Home.module.css
file inside of the styles
folder. Thankfully, Next.js has built-in support for CSS Modules
1
import styles from '../styles/Home.module.css'
9
title: "San Francisco",
29
title: "Oklahoma City",
37
title: "Indianapolis",
43
export default function Home() {
45
<div className={styles.container}>
46
<div className={styles.projectContainer}>
48
projects.map( (project, index) => {
49
return <div key={index}>
50
<p>{project.title}</p>
Here's a couple of important things to note about the CSS:
- Line 16: We use negative
margin
to overlap the divs - Line 17: We give the each div a
background-color: white
to hide the div beneath it
We should have something like this
Animating In and Out
To animate the divs, we're going to use GSAP for it. To use the library, make sure to install it by using npm install gsap
.
With the help of GSAP, we can adjust the divs properties to complete the animation:
3
export default function Home() {
5
const manageMouseEnter = (e, index) => {
6
gsap.to(e.target, {top: "-2vw", backgroundColor: projects[index].color, duration: 0.3})
9
const manageMouseLeave = (e, index) => {
10
gsap.to(e.target, {top: "0", backgroundColor: "white", duration: 0.3, delay: 0.1})
14
<div className={styles.container}>
15
<div className={styles.projectContainer}>
17
projects.map( (project, index) => {
18
return <div onMouseEnter={(e) => {manageMouseEnter(e, index)}} onMouseLeave={(e) => {manageMouseLeave(e, index)}} key={index}>
19
<p>{project.title}</p>
Pretty simple right? Here's the keys to the animation:
- Line 6: We animate in by adjusting the top property of the hovered div and give it its corresponding color.
- Line 10: We animate out by resetting the top property to 0, and the background-color to white.
- Line 5 (css): We add a pointer-events: none to the p to avoid any bugs
Wrapping up
That was it for this animation. Hope you learned a lot, it was quite a simple one, but understanding that negative margin is the key to this animation can be quite tricky. See you next time
Hope you learned a lot :)
- Oli