hover시 가운데에서 퍼져나가는 효과

기성·2025년 8월 12일
0

TIL

목록 보기
90/92

motion 라이브러리를 사용하면서 헤더의 메뉴에 hover 했을 때 가운데에서 밑줄이 퍼져나가는 효과를 만들다가 기록한다.

동영상 왜이렇게 잘렸지

const NavItem = ({ item }: { item: string }) => {
  const location = useLocation();
  const isActive = location.pathname === `/${item.toLowerCase()}`;

  return (
    <motion.div
      className="relative cursor-pointer py-2 px-3"
      whileHover="hovered"
      initial="rest"
      animate={isActive ? "hovered" : "rest"}
    >
      <Link to={`/${item.toLowerCase()}`} className="text-gray-800 font-bold">
        {item}
      </Link>

      <motion.div
        className="absolute left-0 bottom-[-4px] h-[2px] bg-black"
        variants={{
          hovered: { width: "100%" },
          rest: { width: 0, left: "50%", transform: "translateX(-50%)" },
        }}
        transition={{ duration: 0.3 }}
      />
    </motion.div>
  );
};

export default NavItem;

요점은

left: 50%;
transform: "translateX(-50%)";

였다.

이 속성 없이 그냥 애니메이션을 준다면 왼쪽부터 오른쪽으로 퍼져나가는 형식의 모션이 구현된다.
반대로 하려면 right: 0;을 주어 적용하면 된다.

처음에는 그저 border-bottom을 늘리면 되는게 아닌가? 싶었는데 absolute를 통해 div를 배치시키고 나타났다 사라지는 효과를 줬어야 했다.

profile
프론트가 하고싶어요

0개의 댓글