아래와 같이 공통으로 사용될 여러 속성들을 묶어서 mixin을 정의하고 변수로 각 속성에 대한 속성 적용 값을 제공하는 것이다.
// mixin 정의
@mixin custom-style($color, $padding, $border-radius) {
background-color: $color;
padding: $padding;
border-radius: $border-radius;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
font-size: 16px;
font-weight: bold;
}
// mixin 적용
.button {
@include custom-style(#007bff, 10px 20px, 5px);
}
.card {
@include custom-style(#f0f0f0, 20px, 10px);
}
2️⃣-1️⃣ 자주 사용할 것 같은 공통의 속성들 mixin 정의하기
// 버튼 호버 mixin
@mixin button-hover-style($color1, $color2, $font-weight) {
background-color : $color1;
color : $color2;
font-weight: $font-weight;
cursor: pointer;
}
// 버튼 보통 스타일
@mixin button-style($color1, $color2,$font-size,$font-weight, $boder-radious) {
background-color : $color1;
color : $color2;
font-size: $font-size;
font-weight: $font-weight;
border-radius:$boder-radious;
border: none;
cursor: pointer;
}
//버튼 텍스트 가운데 정렬 스타일
@mixin button-center-style(){
display: flex;
align-items: center;
justify-content: center;
}
//버튼 사이즈 버튼
@mixin button-size-style($width, $height){
width: $width;
height: $height;
}
위와 같이 버튼에서 사용할 수 있는 속성들에 대해서 정의하였다.
2️⃣-1️⃣ 적용 전
.shortbutton_container {
display: flex;
.shorthbutton {
height: 40px;
flex-shrink: 0;
min-width: 70px;
padding: 0px 17px;
background-color: $color-1;
border-radius: 8px;
border: none;
display: flex;
align-items: center;
justify-content: center;
color: $color-5;
font-size: 15px;
font-weight: 500;
cursor: pointer;
&:hover {
background-color: $color-4;
color: $color-2;
transition: background-color 500ms ease, color 500ms ease;
}
}
}
2️⃣-2️⃣ 적용후
.shortbutton_container{
display: flex;
.shorthbutton{
@include button-style($color-1, $color-5,15px,500,8px);
@include button-size-style(90px, 40px);
flex-shrink: 0;
padding: 0px 15px;
@include button-center-style();
&:hover{
@include button-hover-style($color-4, $color-2, 500);};
}
}
☑️ 결과
최종적으로 SCSS @mixin을 사용해서 약 43%정도의 코드를 감소할 수 있었다. 앞으로는 새로운 기술이나 기능을 사용할 때 더 깊이 있는 이해와 계획을 가지고 접근해야겠다는 생각을 하게 되었고 이를 통해 더 나은 코드를 작성할 수 있어 즐겁다.