✍️
cssadvand
cssadvand
cssadvand
  • [BEM] Exploring SMACSS: Scalable and Modular Architecture for CSS
  • aspect-ratio thuộc tính giúp tạo hình vuông tuyệt đối square (ok)
  • Animation Anh Huy
    • Ứng dụng
      • Áp dụng thực tế
  • 😀CSS-only infinite scrolling carousel animation (ok)
  • css carousel
  • Rotate3d sử dụng các tham số như nào?
  • 🤡 Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 1)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 2)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 3)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 4)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 5)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 6)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 7)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 8)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 9)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 10)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 11)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 12) [Phần đặc biệt]
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 13)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 14)
  • 😘Thuộc tính tabindex="-1" không ngờ lại nguy hiểm vậy đọc bài dưới 😌
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 15)
  • 🥸CSS tạo theme cho dark mode đọc bài (Phần 16)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 16)
  • Mẹo để optimize Google Fonts API mà ít dev để ý đọc (Phần 17)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 17)
  • Thật may nhờ có white-space: pre-line đọc (Phần 18)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 18)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 19)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 20)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 21)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 22)
  • Thuộc tính image-rendering nhờ bài (Phần 23) mà phát hiện ra cách làm bức ảnh mờ trở nên rõ nét
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 23)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết 🤡
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 24)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 25)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 26)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 27)
  • 😘mix-blend-mode pha trộn giữa 1 đối tượng với đối tượng bên dưới đó (Phần 28)
    • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 28)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 29)
  • 🥸aspect-ratio (Phần 30)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 30)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 31)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 32)
  • Một vài thủ thuật CSS mà chính Frontend có thể còn chưa biết (Phần 33)
  • 😘CSS Scroll Triggered Animations Full (ok)
  • 🥹Difference between animation and transition in CSS
  • 😄animation-timeline có phải nó làm việc với thanh cuộn (ok)
  • 😍Từ bài animation-timeline làm việc với thanh cuộn tìm ra cách sử dụng background-clip: text;
  • background-clip: text;
  • 😅Sử dụng list-style-type để tạo icon đẹp (ok)
  • 😁Convert css to scss good (ok)
  • 😁CSS - Hướng dẫn: Tạo ảnh động với hàm steps()
  • 😆Multiple image cross fading in CSS - without (java) khá đẹp script (ok)
  • 😇Function css full 🤩
  • 😅[SVG] SVG viewBox Attribute (ok)
  • 😅Tailwind CSS (ok)
  • 😍Thật không thể tin được sử dụng filter: brightness(0) invert(1); để chuyển màu ảnh 🤣
  • 😅Background text matter.vn (ok)
  • 😆Chọn màu, color, color contrast ratio (ok)
  • 😁Tổng hợp Animating SVG text cực đẹp (ok)
  • 😂Chuyển động tròn :(
  • 😆MOVE-BG mepop.vn (ok)
  • 😆Counter Increment list, number xuongkhopbacninh.com (ok)
  • Boxes That Fill Height, full Height(Or More) (and Don’t Squish) (ok)
  • Equal Height (chiều cao bằng nhau) (oK)
  • 😅Sử dụng nodejs và scss cấu trúc thư mục tốt P.1(ok)
  • 🥲Sử dụng nodejs và js cấu trúc thư mục tốt P.2 (ok)
  • === START STUDY P.1 && P.2 SỬ DỤNG NODEJS VÀ CẤU TRÚC ===
  • 😉1 Giao diện sử dụng thuộc tính data-coreui-toggle="dropdown" (ok)
  • === END STUDY P.1 && P.2 SỬ DỤNG NODEJS VÀ CẤU TRÚC ===
  • 😆Css box-shadow đẹp (ok)
  • === START Tutorials Classical BEM stack ===
  • 😀HTML with BEM (ok)
  • 😀CSS with BEM (ok)
  • === END Tutorials Classical BEM stack ===
  • === START SMACSS ===
  • Categorizing CSS Rules
  • Base Rules
  • Layout Rules
  • Module Rules
  • State Rules
  • Theme Rules
  • Changing State
  • === END SMACSS ===
  • All CSS Grid Properties (ok)
  • 😇Column Grid full example(Responsive)
  • === Start Điều quan trọng nhất cách chia cột và thay đổi vị trí ===
  • CSS Grid căn bản - Phần 1
  • CSS Grid căn bản - Phần 2
  • CSS Grid: Holy Grail Layout
  • Sử dụng CSS Grid để xây dựng web layout
  • Luyện tập CSS Grid qua bài tập tạo layout Airbnb, youtube, Pinterest
  • === End Điều quan trọng nhất cách chia cột và thay đổi vị trí ===
  • Overflow:hidden dots at the end full (ok)
  • Gulp để viết Sass && cai dat
  • Cách nhúng font vào svg (ok)
  • font-face Hướng dẫn conver font và nhúng sử dụng online (ok)
  • 😇Create CSS Animations on Scroll (ok)
  • Hiệu ứng hover bằng js hiện phần description (ok)
  • Text Link on Hover phần 1 (ok)
  • Kết hợp transition & transform-origin phần 2 (ok)
  • Text Hover Phần 3 (ok)
  • Social Media Icons hover effect (ok)
  • css rotate a pseudo :after or :before content:""
  • Hiệu ứng ảnh tự zoom, animation, scale phần 1 full (ok)
  • CodePen Home Image zoom on hover - auto run - view (ok)
  • scroll-padding (ok)
  • Tạo vòm giống styleathome (ok)
  • Tổng hợp những css đẹp để làm trang trí (ok)
  • Cách thay đổi màu svg full (ok_)
  • Disable Auto Zoom in Input “Text” tag - Safari on iPhone (ok)
  • function calc css (ok)
  • Get the scroll distance from bottom to scroll, var distanceFromBottom (ok) vinmec.com (ok)
  • ---------- Start CSSscan không sử dụng ----------------------
  • Unused CSSscan your website for unused CSS selectors (ok)
  • PurifyCSS OnlineRemove unused CSS code from your stylesheets (ok)
  • Remove unused CSS styles from Bootstrap using PurgeCSS (ok)
  • 😆Thêm column, media bootstrap, custom bootstrap (ok)
  • ---------- End CSSscan không sử dụng ----------------------
  • Xây dựng blog đơn giản (Node + React)
  • Các tham số của Gulp
  • File đã thực hành với Gulp (ok
  • gulp-livereload (chưa đọc)
  • Tối ưu hiệu năng Google Fonts (ok)
  • Cách nhúng font dùng 1 tên và chỉ khác src, font-weight (ok)
  • Học CSS GRID thông qua những layout phức tạp
  • [GRID] sử dụng grid xây dựng layout giống Masonry (ok)
  • PageSpeed Insights Chrome Extension (ok)
  • Tăng tốc website bằng cách cải thiện front-end
  • Code chuẩn SEO là gì
  • 10 CSS3 Animation Tools phổ biến
  • Trang check SEO OKE
  • Làm sao để SEO từ khóa?
  • Kiểm soát web typography với việc hiển thị CSS font (ok)
  • Các mẫu phông chữ hiển thị và thuộc tính hiển thị phông chữ của CSS
  • Một số mẹo tối ưu hóa HTML/CSS/JS đúng chuẩn
  • Web Performance
  • Preload, Prefetch, Preconnect (ok)
  • Tối ưu hóa phần Front end cho trình duyệt (part 1)
  • Tối ưu hóa phần Front end cho trình duyệt (part 2)
  • Sử dụng thuộc tính attr html && css (ok)
  • Disable Auto Zoom in Input “Text” tag - Safari on iPhone (ok)
  • CSS submit button weird rendering on iPad/iPhone submit color (ok)
  • Turn off iPhone/Safari input element rounding (ok)
  • scroll bongda.com.vn (ok)
  • Làm chiếc xe ô tô chuyển động giống 2020.yp.vn (ok)
  • Sự khác biệt giữa :empty và :blank trong CSS (ok)
  • Is there a CSS parent selector? (ok)
Powered by GitBook
On this page
  • Cách sử dụng css thông thường
  • Bước 1: Cập nhật HTML/JSX
  • Bước 2.1: Thêm và gỡ class show sử dụng useEffect để xử lý IntersectionObserver
  • Bước 2.2 Thêm setTimeout khi rời khỏi Giúp tránh việc lập tức xóa show, tạo cảm giác trơn tru:
  • Bước 3: Thêm CSS
  • Cách sử dụng tailwind
  • 1. Tailwind CSS: Định nghĩa lớp fade-in
  • 2. CSS thêm class ẩn ban đầu
  • 3. JSX Component với IntersectionObserver (React)
  • 😍 4. Mở rộng thêm để hỗ trợ animate delay theo thứ tự (kiểu stagger effect) khi scroll đến không
  • Build thêm ví dụ multi-section scroll animation với GSAP trong React
  • — Nếu bạn muốn mình build một landing page kiểu "scroll storytelling" với GSAP (sticky + animation từng phần + số đếm + ảnh phóng to), mình có thể làm mẫu hoàn chỉnh.
  • 🎯 Mục tiêu:
  • Tuyệt! Bây giờ ta sẽ mở rộng landing page với animation có tính responsive, tức là:
  • video scroll sync

Was this helpful?

  1. Animation Anh Huy

Ứng dụng

PreviousAnimation Anh HuyNextÁp dụng thực tế

Last updated 24 days ago

Was this helpful?

Phân tích theo các bước

Cách sử dụng css thông thường

Bước 1: Cập nhật HTML/JSX

<main className="items-center pt-16 pb-4">
  <div className="spacer"></div> 
  <div className="container">
    <div className="box box-red">Đỏ</div>
    <div className="box box-blue">Xanh</div>
    <div className="box box-green">Lá</div>
    <div className="box box-purple">Tím</div>
  </div>
</main>

Bước 2.1: Thêm và gỡ class show sử dụng useEffect để xử lý IntersectionObserver

 useEffect(() => {
    const boxes = document.querySelectorAll('.box');
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          const el = entry.target;
          if (entry.isIntersecting) {
            el.classList.add('show');
          } else {
            el.classList.remove('show');
          }
        });
      },
      {
        threshold: Array.from({ length: 11 }, (_, i) => i / 10), // 0, 0.1, 0.2,...1
      }
    );
    boxes.forEach(box => observer.observe(box));
    return () => boxes.forEach(box => observer.unobserve(box));
  }, []);

Bước 2.2 Thêm setTimeout khi rời khỏi Giúp tránh việc lập tức xóa show, tạo cảm giác trơn tru:

useEffect(() => {
    const boxes = document.querySelectorAll('.box');
    const timeoutMap = new Map();
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          const el = entry.target;
          if (entry.isIntersecting) {
            clearTimeout(timeoutMap.get(el)); // Hủy bỏ nếu có timeout đang chờ xóa
            el.classList.add('show');
          } else {
            // Trì hoãn việc xóa class
            const timeoutId = setTimeout(() => {
              el.classList.remove('show');
            }, 300); // ví dụ 300ms sau mới xóa

            timeoutMap.set(el, timeoutId);
          }
        });
      },
      {
        threshold: Array.from({ length: 11 }, (_, i) => i / 10),
      }
    );
    boxes.forEach(box => observer.observe(box));
    return () => {
      boxes.forEach(box => observer.unobserve(box));
      timeoutMap.forEach(timeoutId => clearTimeout(timeoutId));
    };
  }, []);

Bước 3: Thêm CSS

.spacer {
  height: 100vh;
}
.box {
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.5s ease, transform 0.5s ease;
}
.box.show {
  opacity: 1;
  transform: translateY(0);
}

app\welcome\welcome.tsx

import { useEffect } from 'react';
export function Welcome() {
  useEffect(() => {
    const boxes = document.querySelectorAll('.box');
    const timeoutMap = new Map();
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          const el = entry.target;
          if (entry.isIntersecting) {
            clearTimeout(timeoutMap.get(el)); // Hủy bỏ nếu có timeout đang chờ xóa
            el.classList.add('show');
          } else {
            // Trì hoãn việc xóa class
            const timeoutId = setTimeout(() => {
              el.classList.remove('show');
            }, 300); // ví dụ 300ms sau mới xóa
            timeoutMap.set(el, timeoutId);
          }
        });
      },
      {
        threshold: Array.from({ length: 11 }, (_, i) => i / 10),
      }
    );
    boxes.forEach(box => observer.observe(box));
    return () => {
      boxes.forEach(box => observer.unobserve(box));
      timeoutMap.forEach(timeoutId => clearTimeout(timeoutId));
    };
  }, []);
  return (
    <main className="items-center pt-16 pb-4">
      <div className="spacer"></div>
      <div className="container-flex">
        <div className="box box-red">Đỏ</div>
        <div className="box box-blue">Xanh</div>
        <div className="box box-green">Lá</div>
        <div className="box box-purple">Tím</div>
      </div>
    </main>
  );
}

app\app.css

@import "tailwindcss";
.spacer {
  height: 100vh;
}
.box {
  width: 120px;
  height: 120px;
  border-radius: 12px;
  color: white;
  font-weight: bold;
  opacity: 0;
  transform: translateY(30px);
  transition: opacity 0.6s ease, transform 0.6s ease;
}
.box-red {
  background-color: #e74c3c;
}
.box-blue {
  background-color: #3498db;
}
.box-green {
  background-color: #2ecc71;
}
.box-purple {
  background-color: #9b59b6;
}
.box.show {
  opacity: 1;
  transform: translateY(0);
}

Cách sử dụng tailwind

1. Tailwind CSS: Định nghĩa lớp fade-in

// tailwind.config.js
module.exports = {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      keyframes: {
        'fade-in-up': {
          '0%': { opacity: '0', transform: 'translateY(20px)' },
          '100%': { opacity: '1', transform: 'translateY(0)' },
        },
      },
      animation: {
        'fade-in-up': 'fade-in-up 0.6s ease-out forwards',
      },
    },
  },
  plugins: [],
}

2. CSS thêm class ẩn ban đầu

/* src/index.css hoặc trong component nếu scoped */
.box {
  @apply opacity-0 translate-y-5 transition-all duration-700 ease-out;
}

.box.show {
  @apply opacity-100 translate-y-0;
}

Hoặc nếu dùng animation Tailwind custom ở trên:

.box {
  @apply opacity-0;
}
.box.show {
  @apply animate-fade-in-up;
}

Với tailwind css mới bạn khai báo app\app.css

@import "tailwindcss";
.spacer {
  height: 100vh;
}
@theme {
  --animate-fade-in-up: fade-in-up 1s ease-in-out;
  @keyframes fade-in-up {
    0% {
      opacity: 0;
      transform: translateY(20px);
    }
    100% {
      opacity: 1;
      transform: translateY(0)
    }
  }
}
.box-red {
  background-color: #e74c3c;
}
.box-blue {
  background-color: #3498db;
}
.box-green {
  background-color: #2ecc71;
}
.box-purple {
  background-color: #9b59b6;
}
.box {
  @apply opacity-0;
}
.box.show {
  @apply animate-fade-in-up;
}

3. JSX Component với IntersectionObserver (React)

import { useEffect } from 'react';
const MyComponent = () => {
  useEffect(() => {
    const boxes = document.querySelectorAll('.box');
    const observer = new IntersectionObserver(
      entries => {
        entries.forEach(entry => {
          const el = entry.target;
          if (entry.isIntersecting && entry.intersectionRatio >= 0.1) {
            el.classList.add('show');
          } else if (entry.intersectionRatio < 0.1) {
            el.classList.remove('show');
          }
        });
      },
      {
        threshold: Array.from({ length: 11 }, (_, i) => i / 10), // 0 → 1
      }
    );
    boxes.forEach(box => observer.observe(box));
    return () => boxes.forEach(box => observer.unobserve(box));
  }, []);
  return (
    <main className="items-center pt-16 pb-4">
      <div className="spacer h-screen" />
      <div className="container space-y-8">
        <div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
        <div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
        <div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
        <div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
      </div>
    </main>
  );
};

export default MyComponent;

😍 4. Mở rộng thêm để hỗ trợ animate delay theo thứ tự (kiểu stagger effect) khi scroll đến không

Tuyệt! Hãy mở rộng code của bạn để có hiệu ứng staggered animation – tức là các phần tử xuất hiện dần dần theo thứ tự, giống như slide trong hero hoặc gallery đẹp mắt.

Ý tưởng:

Khi các .box trở nên visible, ta sẽ:

  1. Thêm class show để kích hoạt animation.

  2. Gán delay tăng dần bằng style.animationDelay = ... (hoặc style.transitionDelay nếu dùng transition).

✅ Cập nhật Tailwind config (nếu dùng animate-fade-in-up)

Đã có sẵn:

extend: {
  keyframes: {
    'fade-in-up': {
      '0%': { opacity: '0', transform: 'translateY(20px)' },
      '100%': { opacity: '1', transform: 'translateY(0)' },
    },
  },
  animation: {
    'fade-in-up': 'fade-in-up 0.6s ease-out forwards',
  },
},

✅ CSS (Tailwind class)

.box {
  @apply opacity-0;
}
.box.show {
  @apply animate-fade-in-up;
}

✅ JavaScript (với stagger effect)

import { useEffect } from 'react';
const MyComponent = () => {
  useEffect(() => {
    const boxes = document.querySelectorAll('.box');
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          const el = entry.target as HTMLElement;
          const allVisibleBoxes = Array.from(boxes).filter((b) => {
            const rect = b.getBoundingClientRect();
            return rect.top < window.innerHeight && rect.bottom > 0;
          });
          if (entry.isIntersecting && entry.intersectionRatio >= 0.1) {
            // Tính thứ tự để delay
            const index = allVisibleBoxes.indexOf(el);
            // Gán delay động
            el.style.animationDelay = `${index * 150}ms`;
            el.classList.add('show');
          } else if (entry.intersectionRatio < 0.1) {
            el.classList.remove('show');
            el.style.animationDelay = '0ms';
          }
        });
      },
      {
        threshold: Array.from({ length: 11 }, (_, i) => i / 10),
      }
    );

    boxes.forEach((box) => observer.observe(box));
    return () => boxes.forEach((box) => observer.unobserve(box));
  }, []);

  return (
    <main className="items-center pt-16 pb-4">
      <div className="spacer h-screen" />
      <div className="container space-y-8">
        <div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
        <div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
        <div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
        <div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
      </div>
    </main>
  );
};

export default MyComponent;

intersectionRatio là tỷ lệ phần tử đang hiển thị so với toàn bộ kích thước của nó (giá trị từ 0 đến 1).

✅ Hiệu ứng đạt được:

  • Khi cuộn đến .box, chúng lần lượt hiện lên với delay 0ms, 150ms, 300ms…

  • Khi cuộn ra ngoài, chúng fade-out đồng thời

  • Mượt, tự nhiên, dễ custom!


🔧 Mẹo mở rộng:

  • Thay 150ms bằng biến như baseDelay để dễ tùy chỉnh

  • Dùng data-index để kiểm soát thứ tự nếu cần

  • Dùng transition-delay nếu bạn muốn dùng @apply transition-* thay vì animation

Làm thêm phiên bản dùng GSAP dùng React để animation nâng cao hơn

Tuyệt vời! Dưới đây là phiên bản nâng cao sử dụng GSAP (GreenSock Animation Platform) trong React để tạo hiệu ứng scroll-triggered stagger animation – rất mượt, chuyên nghiệp hơn so với chỉ dùng CSS.


✅ 1. Cài đặt GSAP và ScrollTrigger

npm install gsap

Sau đó, trong code bạn register plugin ScrollTrigger.


✅ 2. React Component với GSAP + Stagger Scroll Animation

timport { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const GSAPBoxes = () => {
  const containerRef = useRef(null);

  useEffect(() => {
    const boxes = gsap.utils.toArray('.box');

    gsap.from(boxes, {
      opacity: 0,
      y: 40,
      duration: 0.8,
      ease: 'power3.out',
      stagger: 0.2,
      scrollTrigger: {
        trigger: containerRef.current,
        start: 'top 80%',
        toggleActions: 'play none none reverse', // fade out when scrolled back
      },
    });
  }, []);

  return (
    <main className="pt-16 pb-4">
      <div className="spacer h-screen" />
      <div ref={containerRef} className="container space-y-8">
        <div className="box bg-red-500 text-white p-6 rounded-xl shadow-md">Đỏ</div>
        <div className="box bg-blue-500 text-white p-6 rounded-xl shadow-md">Xanh</div>
        <div className="box bg-green-500 text-white p-6 rounded-xl shadow-md">Lá</div>
        <div className="box bg-purple-500 text-white p-6 rounded-xl shadow-md">Tím</div>
      </div>
    </main>
  );
};

export default GSAPBoxes;

✅ 3. Tùy chọn CSS (cho mượt ban đầu)

/* index.css */
.box {
  will-change: transform, opacity;
}

✅ Giải thích:

Thành phần
Vai trò

gsap.from(...)

Animate các .box từ opacity: 0 và y: 40px

stagger: 0.2

Delay mỗi box 0.2 giây → tạo hiệu ứng "xuất hiện theo hàng"

ScrollTrigger

Kích hoạt animation khi scroll đến

toggleActions: 'play none none reverse'

Khi rời khỏi viewport, các box sẽ fade out ngược


✅ Muốn nâng cao thêm?

  • 📦 Animate từng nhóm khi scroll xuống sâu hơn

  • 🔁 Lặp lại animation mỗi lần scroll (dùng toggleActions)

  • 🧲 Kết hợp GSAP + Tailwind + clipPath, scale, v.v.


✅ Khi nào dùng GSAP thay vì CSS?

Dùng CSS
Dùng GSAP

Hiệu ứng đơn giản: fade, slide

Các hiệu ứng nâng cao: timeline, physics, scrub, delay

Nhẹ, nhanh, native với Tailwind

Cần kiểm soát sâu: khi bắt đầu, khi kết thúc, trigger phức tạp

Không cần thư viện ngoài

Sẵn sàng tải thêm GSAP để có UX nâng cao

Build thêm ví dụ multi-section scroll animation với GSAP trong React

Tuyệt! Dưới đây là một ví dụ multi-section scroll animation dùng GSAP + ScrollTrigger trong React.

Bạn sẽ thấy:

  • Mỗi section animate khi cuộn tới

  • Các section slide lên + fade-in

  • Có thể mở rộng thêm timeline, scrub, parallax v.v.


✅ 1. Cài đặt

npm install gsap

✅ 2. Tạo Component: MultiSectionScroll.tsx

import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const sections = [
  { id: 1, color: 'bg-red-500', label: 'Section 1' },
  { id: 2, color: 'bg-blue-500', label: 'Section 2' },
  { id: 3, color: 'bg-green-500', label: 'Section 3' },
  { id: 4, color: 'bg-purple-500', label: 'Section 4' },
];

const MultiSectionScroll = () => {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const sectionEls = gsap.utils.toArray('.section') as HTMLElement[];

    sectionEls.forEach((el, index) => {
      gsap.fromTo(
        el,
        { opacity: 0, y: 50 },
        {
          opacity: 1,
          y: 0,
          duration: 0.8,
          ease: 'power3.out',
          scrollTrigger: {
            trigger: el,
            start: 'top 80%',
            toggleActions: 'play none none reverse',
            markers: false, // set true for debug
          },
        }
      );
    });
  }, []);

  return (
    <div ref={containerRef} className="space-y-32 py-20">
      {sections.map((s) => (
        <section
          key={s.id}
          className={`section ${s.color} text-white text-3xl font-bold h-[80vh] flex items-center justify-center rounded-2xl shadow-lg mx-4`}
        >
          {s.label}
        </section>
      ))}
    </div>
  );
};

export default MultiSectionScroll;

✅ 3. Styles (Tailwind)

/* You can also use global styles if needed */
.section {
  will-change: transform, opacity;
}

✅ Kết quả:

  • 4 Section xuất hiện khi cuộn tới.

  • Mỗi section fade-in + slide-up riêng biệt.

  • Reverse animation khi cuộn ngược lại (nếu cần).

  • Rất mượt và chuyên nghiệp với GSAP.


✅ Mở rộng gợi ý:

Ý tưởng
Cách làm

Parallax scroll effect

Dùng ScrollTrigger + scrub: true

Stagger từng phần tử trong section

Dùng gsap.timeline() + stagger

Fixed background scroll reveal

Dùng pin của ScrollTrigger

Animate ảnh, tiêu đề, text riêng

Tách selector & gán timeline riêng


— Nếu bạn muốn mình build một landing page kiểu "scroll storytelling" với GSAP (sticky + animation từng phần + số đếm + ảnh phóng to), mình có thể làm mẫu hoàn chỉnh.

Tuyệt! Hãy cùng xây dựng một landing page dạng scroll storytelling với các kỹ thuật nâng cao từ GSAP + React.


🎯 Mục tiêu:

  • Hero section (fade-in)

  • Scroll xuống:

    • Section 1: ảnh zoom + text hiện

    • Section 2: số đếm (counter) khi visible

    • Section 3: sticky + scroll reveal

  • Sử dụng GSAP + ScrollTrigger + Timeline


✅ 1. Cài đặt

npm install gsap

✅ 2. File ScrollStory.tsx – Landing page

import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const ScrollStory = () => {
  const heroRef = useRef(null);
  const zoomRef = useRef(null);
  const counterRef = useRef(null);
  const stickyRef = useRef(null);

  useEffect(() => {
    // Hero fade in
    gsap.from(heroRef.current, {
      opacity: 0,
      y: -30,
      duration: 1,
      ease: 'power3.out',
    });

    // Zoom image
    gsap.from(zoomRef.current, {
      scale: 0.8,
      opacity: 0,
      duration: 1,
      scrollTrigger: {
        trigger: zoomRef.current,
        start: 'top 80%',
        toggleActions: 'play none none reverse',
      },
    });

    // Counter animation
    const counterEl = counterRef.current as HTMLElement;
    let counterTriggered = false;

    ScrollTrigger.create({
      trigger: counterEl,
      start: 'top 80%',
      onEnter: () => {
        if (!counterTriggered) {
          const updateCount = () => {
            let count = 0;
            const target = 100;
            const increment = 2;

            const interval = setInterval(() => {
              count += increment;
              counterEl.innerText = count.toString();
              if (count >= target) clearInterval(interval);
            }, 20);
          };
          updateCount();
          counterTriggered = true;
        }
      },
    });

    // Sticky + scroll-reveal
    gsap.from(stickyRef.current, {
      y: 100,
      opacity: 0,
      duration: 1,
      scrollTrigger: {
        trigger: stickyRef.current,
        start: 'top 60%',
        end: 'bottom top',
        scrub: true,
        pin: true,
      },
    });
  }, []);

  return (
    <div className="font-sans text-gray-900 leading-relaxed">
      <section
        ref={heroRef}
        className="h-screen flex items-center justify-center bg-gradient-to-br from-indigo-500 to-purple-600 text-white text-5xl font-bold"
      >
        Chào mừng bạn đến Landing Page 🎉
      </section>

      <section className="h-screen flex items-center justify-center bg-white">
        <div ref={zoomRef} className="max-w-md">
          <img
            src="https://source.unsplash.com/600x400/?nature"
            alt="Zoom image"
            className="rounded-xl shadow-lg"
          />
          <p className="mt-6 text-center text-xl font-semibold">Khám phá thiên nhiên</p>
        </div>
      </section>

      <section className="h-screen flex flex-col items-center justify-center bg-gray-100">
        <div className="text-4xl font-bold mb-4">Số khách truy cập:</div>
        <div
          ref={counterRef}
          className="text-6xl font-extrabold text-indigo-600"
        >
          0
        </div>
      </section>

      <section className="h-screen bg-yellow-100 flex items-center justify-center">
        <div
          ref={stickyRef}
          className="bg-yellow-300 text-3xl font-bold p-8 rounded-xl shadow-md"
        >
          Nội dung được ghim khi scroll!
        </div>
      </section>
    </div>
  );
};

export default ScrollStory;

✅ 3. Kết quả:

Section
Animation

Hero

Fade-in khi page load

Zoom section

Ảnh scale + fade khi scroll đến

Counter

Số đếm từ 0 → 100 khi phần tử vào viewport

Sticky section

Ghim + di chuyển nội dung theo scroll bằng scrub + pin


✅ Gợi ý mở rộng:

  • 👉 Add gsap.timeline() cho các animation liên tiếp trong 1 section

  • 👉 Add scrub: true để tạo hiệu ứng mượt scroll-trigger

  • 👉 Add motion path, clipPath, text split, parallax…


Bạn muốn mình tiếp tục thêm:

  • 📊 chart animation

  • 🎬 video + scroll sync

  • 📱 responsive animation

  • 🧠 animate SVG path

Tuyệt! Bây giờ ta sẽ mở rộng landing page với animation có tính responsive, tức là:

✅ Mục tiêu:

  1. Animation khác nhau tùy theo kích thước màn hình (VD: mobile vs desktop)

  2. Giữ trải nghiệm mượt mà trên mọi thiết bị

  3. Kết hợp GSAP + ScrollTrigger + Media Queries


✅ 🧠 Cách xử lý responsive với GSAP:

GSAP ScrollTrigger hỗ trợ media query logic bằng:

ScrollTrigger.matchMedia({
  '(min-width: 768px)': () => { /* Desktop animation */ },
  '(max-width: 767px)': () => { /* Mobile animation */ },
});

🧪 Ví dụ: Responsive Scroll Animation (GSAP)

import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const ResponsiveScroll = () => {
  const zoomRef = useRef(null);

  useEffect(() => {
    ScrollTrigger.matchMedia({
      // ✅ Desktop
      '(min-width: 768px)': () => {
        gsap.fromTo(
          zoomRef.current,
          { scale: 0.8, opacity: 0, x: 100 },
          {
            scale: 1,
            opacity: 1,
            x: 0,
            duration: 1,
            ease: 'power3.out',
            scrollTrigger: {
              trigger: zoomRef.current,
              start: 'top 80%',
              toggleActions: 'play none none reverse',
            },
          }
        );
      },

      // ✅ Mobile
      '(max-width: 767px)': () => {
        gsap.fromTo(
          zoomRef.current,
          { scale: 0.9, opacity: 0, y: 50 },
          {
            scale: 1,
            opacity: 1,
            y: 0,
            duration: 1,
            ease: 'back.out(1.7)',
            scrollTrigger: {
              trigger: zoomRef.current,
              start: 'top 85%',
              toggleActions: 'play none none reverse',
            },
          }
        );
      },
    });
  }, []);

  return (
    <section className="h-screen flex items-center justify-center bg-white">
      <div ref={zoomRef} className="max-w-md text-center">
        <img
          src="https://source.unsplash.com/600x400/?travel"
          alt="Travel"
          className="rounded-xl shadow-lg mx-auto"
        />
        <p className="mt-6 text-xl font-semibold">Khám phá hành trình mới 🌍</p>
      </div>
    </section>
  );
};

export default ResponsiveScroll;

🧩 Giải thích:

Kích thước
Animation

Desktop (≥768px)

scale + fade + slide-in từ phải

Mobile (<768px)

scale + fade + slide-up nhẹ với ease: back.out()

Tối ưu UX

Dễ chịu với thao tác tay trên mobile, mạnh mẽ trên desktop


✅ Pro Tips:

Mục tiêu
Cách làm

✅ Thay đổi duration/ease theo size

ScrollTrigger.matchMedia({})

✅ Ẩn một số animation trên mobile

Đơn giản return null hoặc không tạo timeline

✅ Stagger khác nhau

Thêm stagger: 0.3 trong desktop, và stagger: 0.1 trong mobile

✅ Pin section chỉ ở desktop

Pin với start: 'top top', end: '+=1000', pin: true trong desktop only


✅ Muốn nâng cao hơn?

  • Kết hợp với CSS container queries (sắp phổ biến)

  • Thêm matchMedia.add() để destroy() khi thay kích thước màn hình

  • Kết hợp Framer Motion để có spring + tap/drag/hover interaction


Nếu bạn muốn mình:

  • 👉 Kết hợp nhiều section vào 1 demo hoàn chỉnh (có responsive scroll story)

  • 👉 Tạo video scroll sync, parallax, split text animation cho responsive

  • 👉 Export thành một GitHub repo + Live preview

video scroll sync

Tuyệt! Giờ ta sẽ build một ví dụ 🎬 video scroll sync với GSAP + ScrollTrigger + React, nơi video được điều khiển bằng cuộn chuột (scrub) – hiệu ứng thường thấy trong các landing page cao cấp (Apple, Tesla...).

Tuyệt! Giờ ta sẽ build một ví dụ 🎬 video scroll sync với GSAP + ScrollTrigger + React, nơi video được điều khiển bằng cuộn chuột (scrub) – hiệu ứng thường thấy trong các landing page cao cấp (Apple, Tesla...).


🎯 Mục tiêu:

  • Video không tự play

  • Người dùng scroll để điều khiển thời gian (time) của video

  • Có sticky section giữ video khi cuộn


✅ 1. Cài đặt

npm install gsap

✅ 2. Component: VideoScrollSync.tsx

import { useEffect, useRef } from 'react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const VideoScrollSync = () => {
  const containerRef = useRef(null);
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const video = videoRef.current;

    if (!video) return;

    // Đảm bảo video đã tải đủ dữ liệu để có duration
    video.addEventListener('loadedmetadata', () => {
      const duration = video.duration;

      // ScrollTrigger scrub = video progress
      gsap.to(video, {
        currentTime: duration,
        ease: 'none',
        scrollTrigger: {
          trigger: containerRef.current,
          start: 'top top',
          end: '+=3000', // chiều cao cuộn để điều khiển toàn bộ video
          scrub: true,
          pin: true,
          anticipatePin: 1,
          markers: false, // true để debug
        },
      });
    });
  }, []);

  return (
    <section
      ref={containerRef}
      className="relative h-screen bg-black flex items-center justify-center overflow-hidden"
    >
      <video
        ref={videoRef}
        src="/path-to-your-video.mp4"
        className="w-full h-auto max-h-[90vh] rounded-xl shadow-2xl"
        muted
        preload="auto"
      />
    </section>
  );
};

export default VideoScrollSync;

✅ 3. Ghi chú quan trọng

Điều cần biết
Lý do

video.currentTime

GSAP có thể tween giá trị này để điều khiển playback thủ công

pin: true

Giữ section cố định khi scroll (sticky effect)

end: +=3000

Chiều cao scroll – càng lớn cuộn càng lâu mới hết video

scrub: true

Kéo mượt theo cuộn – không phải bật phát một lần

muted

Trình duyệt chặn autoplay audio nếu không có muted


✅ Đặt file video ở đâu?

  • Nếu bạn dùng Vite:

    • Đặt video vào thư mục public/

    • Gọi như src="/your-video.mp4"

Hoặc import video nếu bạn dùng Webpack / file bundler:

import myVideo from './assets/video.mp4';
<video src={myVideo} ... />

✅ Mở rộng nâng cao

Mục tiêu
Cách làm

📱 Responsive video

Tailwind max-w-[100%], max-h-[90vh], object-contain

🎬 Trigger nội dung khác theo video progress

Dùng ScrollTrigger khác với onUpdate: self => ...

🧠 Scroll từ frame → frame (image sequence)

Dùng frame-by-frame animation thay cho video (nặng hơn)

🎙️ Sync âm thanh / phụ đề

Dùng video.textTracks + cue points


✅ Demo Live (nếu muốn)

Muốn mình build bản đầy đủ:

  • 💡 Bắt đầu từ Hero

  • 📽️ Video scroll-sync

  • ✨ Fade text theo đoạn video

  • 📱 Responsive

  • 🌐 Gửi link Live hoặc GitHub

👉 Chỉ cần nói: Export demo scroll-video Mình build ngay cho bạn!