핵심 Sass | @mixin

Faithful Dev·2025년 4월 3일
0

프리스쿨

목록 보기
14/25

@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에서 같은 스타일을 반복하지 않고 한 번에 재사용할 수 있음

매개변수(Arguments) 활용

@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);를 호출하면 매개변수가 적용됨

기본값(Default 값) 설정

매개변수에 기본값을 설정할 수도 있다.

@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)을 설정해두면, 필요할 때만 값 변경 가능

가변 인자(Variable Arguments)

매개변수 개수를 유동적으로 받을 수도 있다.

@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, 가변 인자, 반응형 미디어 쿼리 등을 활용하면 더 유연하게 사용 가능
  • CSS 코드 반복을 줄이고, 유지보수를 쉽게 만들 수 있음
profile
Turning Vision into Reality.

0개의 댓글