@mixin
은 재사용 가능한 스타일 블록을 정의하는 Sass의 기능이다.
CSS에서 반복적으로 사용되는 스타일(예: 버튼, 박스 쉐도우, 반응형 미디어 쿼리 등)을 한 곳에 모아서 관리할 수 있다.
@mixin 믹스인이름 {
스타일;
}
요소 {
@include 믹스인이름;
}
@mixin
사용@mixin rounded-box {
border-radius: 10px;
padding: 20px;
border: 1px solid #ddd;
}
.card {
@include rounded-box;
background-color: white;
}
.alert {
@include rounded-box;
background-color: red;
color: white;
}
@mixin rounded-box
를 정의한 후, @include rounded-box;
를 사용하여 적용.card
와 .alert
에서 같은 스타일을 반복하지 않고 한 번에 재사용할 수 있음@mixin
은 매개변수를 받을 수 있어, 유연한 스타일 지정이 가능하다.
@mixin rounded-box($radius, $padding, $border-color) {
border-radius: $radius;
padding: $padding;
border: 1px solid $border-color;
}
.card {
@include rounded-box(15px, 25px, #aaa);
}
.alert {
@include rounded-box(5px, 10px, red);
}
@mixin rounded-box($radius, $padding, $border-color)
에서 변수를 활용하여 스타일을 동적으로 생성@include rounded-box(15px, 25px, #aaa);
를 호출하면 매개변수가 적용됨매개변수에 기본값을 설정할 수도 있다.
@mixin button-style($bg-color: blue, $text-color: white) {
background-color: $bg-color;
color: $text-color;
padding: 10px 15px;
border-radius: 5px;
}
.primary-btn {
@include button-style; // 기본값 사용 (파랑 배경, 흰색 텍스트)
}
.secondary-btn {
@include button-style(red, black); // 값 변경 (빨간 배경, 검은색 텍스트)
}
blue
, white
)을 설정해두면, 필요할 때만 값 변경 가능매개변수 개수를 유동적으로 받을 수도 있다.
@mixin text-styles($sizes...) {
font-size: nth($sizes, 1);
line-height: nth($sizes, 2);
}
.title {
@include text-styles(20px, 1.5);
}
$sizes...
는 여러 개의 값을 받는 가변 인자(Variable Argument)@content
로 내부 콘텐츠 사용하기@mixin
내부에 @content
를 사용하면, 호출할 때 추가적인 스타일을 포함할 수 있다.
@mixin box {
padding: 20px;
border: 1px solid #ddd;
@content; // 추가 스타일을 받을 수 있음
}
.card {
@include box {
background-color: white;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
}
@content
를 사용하면 @include
를 호출할 때 추가 스타일을 넣을 수 있음@mixin
을 활용하면 반응형 미디어 쿼리를 더 깔끔하게 관리할 수 있다.
@mixin responsive($breakpoint) {
@if $breakpoint == small {
@media (max-width: 600px) { @content; }
} @else if $breakpoint == medium {
@media (max-width: 900px) { @content; }
} @else if $breakpoint == large {
@media (max-width: 1200px) { @content; }
}
}
.box {
width: 100%;
@include responsive(small) {
width: 50%;
}
@include responsive(medium) {
width: 75%;
}
}
@include responsive(small);
을 사용하면 자동으로 적절한 미디어 쿼리를 적용@mixin
은 재사용 가능한 스타일을 정의하는 기능@include
를 사용하여 정의한 @mixin
을 적용할 수 있음@content
, 가변 인자, 반응형 미디어 쿼리 등을 활용하면 더 유연하게 사용 가능