HTML & CSS
[SCSS] SCSS 도입기
popeyes
2024. 4. 5. 14:11
*SCSS란?
프로젝트의 규모가 커지거나 작업이 고도화 될 수록 가독성이 떨어질 수 밖에 없는 CSS의 단점을 보완하고,
개발의 효율성을 올리기 위해 등장한 것이다.
*어쩌다 도입하게 되었나?
SOPT 과제 중 하나이기 때문에 처음 도입하긴 했지만, 애초에 CSS의 불편함을 느끼고 있었다.
**CSS 뭐가 불편함?
우리는 이런 코드를 자주 사용한다
display:flex;
flex-direction:row
justify-content:center;
align-items:center;
위 코드를 반복적으로 사용해야만 하는 불편함을 느껴 분명 이를 해결해주는 무언가가 있을 것이라 생각했다.
저번 웹잼 프로젝트에서, 우리 팀 동료가 이와 관련해서 mixin 기법을 도입하자고 주장하였다.
(물론 styled components였지만...)
아래는 웹잼 프로젝트 당시 코드 중 일부이다.
그때의 mixin 코드를 가져와 보면,
import { css } from 'styled-components';
interface MixinProps {
direction: string;
align: string;
justify: string;
}
const mixin = {
// flex
flexBox: ({ direction = 'row', align, justify }: MixinProps) => css`
display: flex;
flex-direction: ${direction};
align-items: ${align};
justify-content: ${justify};
`,
inlineFlexBox: ({ direction = 'row', align, justify }: MixinProps) => css`
display: inline-flex;
flex-direction: ${direction};
align-items: ${align};
justify-content: ${justify};
`,
flexCenter: ({ direction = 'column' }: MixinProps) => css`
display: flex;
flex-direction: ${direction};
align-items: center;
justify-content: center;
`,
};
export default mixin;
.
.
.
mixin을 사용하는 쪽에서는
display:flex;
flex-direction:row
justify-content:center;
align-items:center;
위 코드가,
${({ theme }) => theme.mixin.flexBox({ align: 'center', justify: 'center' })}
이렇게 단 한줄로 바뀐다.
이 덕분에 비교적 효율적으로 스타일 코드를 작성할 수 있던 좋은 기억으로,
이번 솝트 과제에서도 비슷하게 도입해보고 싶었다.
따라서 styled components를 제외하고 일반 css로 구현할 수는 없을까 알아보다가 찾은 것이
'SCSS'였다!
한 마디로,
반복되는 코드를 줄이기 위해 도입했다고 요약할 수 있다.
그렇다면 이번 SOPT 과제에서는 어떻게 사용했는지 알아보자.
먼저 mixin에 대해서 설정해준다.
@mixin flex(
$direction: row,
$wrap: nowrap,
$justifyContent: flex-start,
$alignItems: center
) {
display: flex;
flex-direction: $direction;
flex-wrap: $wrap;
justify-content: $justifyContent;
align-items: $alignItems;
}
그 후 사용하는 쪽에서는,
header {
@include flex(row, nowrap, space-between, center);
}
이렇게 한줄로 끝이난다.
찾아보니 SCSS는 mixin기능 이외에도 여러 기능이 있다.
- 중첩을 통해 상위 선택자의 반복을 줄일 수 있는 기능.
- 반복되는 값을 변수로 지정하기.
- 함수, 조건문, 반복문 등.
추후에는 위 기능들도 도입해서 SCSS를 다양한 방면으로 사용하고 싶은 욕심이 생겼다.