Study/SCSS

[SCSS] 믹스인 정의 및 호출, 인자(매개변수)를 사용하는 믹스인

hyjang 2024. 11. 5. 19:19
728x90
  • css를 코드 블록으로 만들어 해당 블록을 재사용

믹스인 정의 및 호출

// @mixin : 믹스인 정의
@mixin common-btn {
    width: 150px;
    height: 50px;
    background: #afafaf;
    border: 2px solid black;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    font-weight: bold;
    margin-bottom: 10px;

    &:hover{
        text-decoration: underline;
        text-underline-position: under;
    }
}

// @include : 믹스인 호출
.btn-1 {
    @include common-btn;
} 

.btn-2 {
    @include common-btn; 
    background: #dfdfdf; // 기본 믹스인보다 우선순위가 높다.(뒤에 쓰였기 때문)
}

인자를 사용하는 믹스인

// @mixin : 믹스인 정의
@mixin common-btn($width: 150px, $height: 50px, $bg-color: #afafaf) { // 매개변수 : 초깃값
    width: $width;
    height: $height;
    background: $bg-color;
    border: 2px solid black;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    font-weight: bold;
    margin-bottom: 10px; 

    &:hover{
        text-decoration: underline;
        text-underline-position: under;
    }
}

// @include : 믹스인 호출
.btn-1 {
    @include common-btn;
} 

.btn-2 { 
    @include common-btn(200px, 70px, red); //인자값 넘기기
}

.btn-3{
    @include common-btn(120px, 50px);
}
💡@include로 보낼 인자값은 순서를 정확하게 전달해야 한다.
인자를 보내지 않는다면 초깃값으로 설정되기 때문에 매개변수에 초깃값을 반드시 기재해야한다.

특정 인자만 넘기는 방법

.btn-4{
    @include common-btn($bg-color: blue);
}