Styeld-Component 애니메이션 추가

sonnng·2023년 1월 3일
0

React

목록 보기
2/8
post-thumbnail

🔷 styled-component에서 애니메이션 주는 방법

1) keyframes 이용
css 그대로 애니메이션을 이용하는 대신, animation을 지정시 ${}이용

import styled from "styled-components";
import { keyframes } from "styled-components";
const Container = styled.div`
  display: flex;
`;
const animation = keyframes`
0%{
  transform:rotate(0deg);
  border-radius:0px;
}
50%{
  transform:rotate(180deg);
  border-radius:30px;
}
100%{
  transform:rotate(360deg);
  border-radius:50px;
}
`;
const Box = styled.div`
  height: 100px;
  width: 100px;
  background-color: beige;
  animation: ${animation} 1s linear infinite;
  display: flex;
  justify-content: center;
  align-items: center;
  span {
    font-size: 20px;
    &:hover {
      font-size: 40px;
    }
  }
`;

function App() {
  return (
    <Container>
      <Box>
        <span>😚</span>
      </Box>
    </Container>
  );
}

export default App;

마우스를 올려두면 이모지 크기가 커지게 하였다.
만약 코드 수정시 span -> p로 변경된다면, 코드 적용이 안된다는 문제점이 있다.

=> component자체를 타겟팅하는 psedo selector이용

const Emoji = styled.span`
  font-size: 20px;
`;

const Box = styled.div`
  height: 100px;
  width: 100px;
  background-color: beige;
  animation: ${animation} 1s linear infinite;
  display: flex;
  justify-content: center;
  align-items: center;
  ${Emoji}:hover {
      font-size: 40px;
    }
  }
`;

이렇게 되면 Box안에 속한 Emoji만이 hover 효과가 적용된다.

0개의 댓글