sass를 한번 쓰게 되면 다시는 css로 못돌아갈 만큼 편리한 sass에 대해서 알아보자!!
[설치] npm install sass
기존의 css파일에서 scss로 바꾸고 import를 하게 되면 스타일이 잘 적용되는 부분도 있지만, 다른 스타일이 적용되어 스타일이 깨지는 모습을 볼 수 있다.
이런 문제가 생기는 이유는 SPA와 연관되어 있다.
MPA환경에서는 각각의 페이지마다 css파일을 독립적으로 import해 사용하기 때문에 선택자가 해당 페이지에서만 중복되지 않으면 됐지만,
SPA 환경에서는 모든 페이지 컴포넌트가 Router.js로 모이고 index.js를 거쳐 index.html에 모이기 때문에 겹치는 선택자가 있다면, 스타일이 깨 질 수 밖에 없다.
위와 같은 문제를 해결하기 위한 방법으로는
className
을 다르게 주기 와 같은 두가지 방법이 있다.
...
<div className="login-wrap">
<h1 className="logo">Westagram</h1>
<form className="login-form">
<div className="input-area">
<input
className="input-id"
type="text"
name="id"
placeholder="전화번호, 사용자 이름 또는 이메일"
/>
<input
className="input-pw"
type="password"
name="password"
placeholder="비밀번호"
/>
<p className="notice">올바른 아이디와 비밀번호를 입력해주세요</p>
</div>
<button className="btn-login">로그인</button>
</form>
</div>
위와 같은 JSX 구조가 있다고 했을 때 nesting문법을 적용한 scss의 모습은 아래와 같을 수 있다.
.login-wrap {
.logo {
font-family: 'Lobster', cursive;
font-size: 40px;
margin-bottom: 40px;
}
.login-form {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
margin-bottom: 100px;
.input-area {
width: 90%;
&.error {
.notice {
display: block;
}
input {
border: 1px solid red;
}
}
input {
width: 100%;
padding: 10px 10px;
margin-bottom: 10px;
background: #fafafa;
border: 1px solid #dbdbdb;
&::placeholder {
color: #999;
}
}
.notice {
display: none;
margin-bottom: 15px;
font-size: 12px;
color: red;
}
}
}
sass
의 nesting
은 마치 HTML구조처럼 login-wrap
로 자식 관계에 있는 스타일을 품고 그 안에 다른 태그 혹은 className들의 스타일을 적용하는 방법으로 구현된 것을 볼 수 있다. 💡sass는 css전처리기이기 때문에 scss문법을 이용해 편리하게 작성한 scss파일을 실제 화면에 그릴 때는 컴퓨터가 읽을 수 있는 css파일로 자동으로 변환해준다!
$primary-color: #0095f6;
.btn-login {
width: 90%;
padding: 8px 0;
background: $primary-color;
border: 1px solid $primary-color;
color: #fff;
font-weight: 500;
border-radius: 4px;
text-align: center;
text-decoration: none;
}
:hover
/ :checked
/ :not
/ 가상요소.btn-login {
width: 90%;
padding: 8px 0;
background: $primary-color;
border: 1px solid $primary-color;
color: #fff;
font-weight: 500;
border-radius: 4px;
text-align: center;
text-decoration: none;
&:disabled {
opacity: 0.5;
}
}
mixin
은 @mixin 변수이름 {여러가지 스타일 속성}
과 같은 형식 @include 변수 이름
을 사용하면 된다. // 선언
@mixin flexCenter{
display:flex,
justify-content: center;
align-items: center;
}
//사용
.signiup{
@include flexCenter;
}
mixin
과 함께 쓸 수 있으며 함수처럼 매개변수와 인자를 쓸 수 있다.// 선언
@mixin flex($justify, $align){
display:flex,
justify-content:$justify;
align-items: $align;
}
//사용
.signiup{
@include flex(center, center);
}
@import "../../styles/variables.scss";
마무리✨
문법이나 스타일 속성 사용하는 것은 css와 크게 다르지 않아서 css에 익숙하다면 scss를 사용도 문제 없을 것 같다. 하지만 mixin이나 변수로 설정하는 것과 같은 개념은 조금 낯설 수 있기 때문에 기존 css를 scss로 변환하면서 많이 사용해보면서 사용법에 익숙해져야 할 것 같다.
css 를 사용할 때 매번 내가 사용하던 색상코드를 까먹어서 위로 올라가서 다시 복붙해오고 이랬던 적이 많아서 은근 불편했었는데 앞으로 scss를 사용하면 좀 더 빠르고 편리하게 작업 할 수 있을 것 같다!!