Styled Components (3)

Jaeheon·2022년 10월 26일
0

Styled Components

목록 보기
4/4
post-thumbnail

Animation and Pseudo Selectors

애니메이션은 기존의 css와 다른점이 딱히 없습니다.
keyframes라는 모듈을 불러와 사용하게 되는데 바로 코드 보시죠.

import styled, {keyframes} from "styled-components";

const Container = styled.div`
  margin: 10px;
`;

const animation = keyframes`
  0%{
    transform:rotate(0deg);
    border-radius: 0px;
  }
  50%{
    transform: rotate(360deg);
    border-radius: 100px;
  }
  100%{
    transform:rotate(0deg);
    border-radius: 0px;
  }
`;

const Box = styled.div`
  height: 50px;
  width: 50px;
  background-color: tomato;
  animation: ${animation} 2s ease-in-out infinite;
`;

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

export default App;

keyframes로 animation을 정의해주고
이 애니메이션을 css animation에 불러와주면 끝입니다.

추가적으로 이모지를 하나 넣어봅시다.

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

만약 이 상태에서 이모지에 특정 스타일을 입히고 싶다면 어떻게 해야할까요?

기존 방식대로라면 span 태그로 styled Components를 만들어서 새로운 컴포넌트를 사용하면 될텐데, 이번엔 좀 다른 방식으로 Selector를 활용해 봅시다.

const Box = styled.div`
  height: 50px;
  width: 50px;
  background-color: tomato;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: ${animation} 2s ease-in-out infinite;

  span{
    font-size: 30px;
  }

`;

단순히 Box 안에 span태그를 cascade형식으로 작성해주는 것으로 끝이 납니다.

만약! 여기서 span태그를 p나 a태그로 바꾸게 되면 당연히 Selector가 동작하지 않겠죠?
이런 경우에 태그에 의존하지 않고 Selector를 작동하고 싶으면 Emoji라는 새로운 컴포넌트를 작성해서 이 친구를 Box 안에서 select 해주면 될 것 같네요.

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

const Box = styled.div`
  height: 50px;
  width: 50px;
  background-color: tomato;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: ${animation} 2s ease-in-out infinite;

  ${Emoji}{
    &:hover{
      font-size: 10px;
    }
  }

`;

hover한 경우 위와 같이 잭오랜턴의 size가 작아집니다.
또한 태그에 상관없이 잘 동작하게 됩니다.

function App() {
  return (
    <Container>
      <Box>
        <Emoji as="p">🎃</Emoji>
      </Box>
    </Container>
  );
}

profile
기록이 습관인 개발자

0개의 댓글