CSS,SCSS

SCSS mixin

Hangyu_Choi 2022. 8. 1. 08:49

css에 반복적으로 사용되는 속성들을 묶어 함수처럼 호출하는 방식

 

선언

@mixin name{
  // code
}

// 또는

@mixin name($arg, $arg1, $arg2, ...) {
  // code
}

 

호출

div{
  @include name;
}

// 또는

div{
  @include name(arg1, arg2, arg3, ...);
}

 

예제

기본값 셋팅도 가능!

// 기존 css
div {
  padding: 0 24px;
  color: green;
  background-color: blue;
}

// mixin을 사용하면
// 선언
@mixin name($arg, $arg2: red, $arg3: blue){
  padding: $arg;
  color: $arg2;
  background-color: $arg3;

}
// 사용
@mixin name(0 24px, green);

 

 

flex box를 mixin 방식으로 사용하면 코드가 간결해 질 수 있다!

// 기존 css 코드
div {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
div > p {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

// mixin을 사용하면
// 선언
@mixin flexBox($fd: row, $jc: flex-start, $ai: flex-start) {
  display: flex;
  flex-direction: $fd;
  justify-content: $jc;
  align-items: $ai;
}

// 사용
div {
  @include flexBox(column);
}
div > p {
  @include flexBox(row, space-between, center);
}