[SCSS]@mixin,@function 사용하기

JEON HAN BIT·2023년 4월 16일
0

SCSS

목록 보기
1/1

@mixin 이란?

재사용 가능한 스타일 코드 , 함수랑 비슷하게 동작함 ( 파라미터 전달 가능 )

mixin 정의하기 (@mixin)

@mixin button ($color:red) {
	color:$color;
    width:32px;
    height:32px;
}

mixin 사용하기 (@include)

.nav-button{
	@include button; // default 값 red
    @include button(blue) // 파라미터로 넘긴값 blue
}

mixin 타입가드,유효성검사 (type-of)

@mixin button ($color:false) {
    @if (type-of($color) == color) { // css 내장 프로퍼티 color
        color: $color;
    }
    width: 32px;
    height: 32px;
}

mixin 활용 예 ( position-mixin 만들기 )

@mixin pos-center-x ($type:absolute) {
    @if($type == fixed or $type == absolute){
        position: $type;
        left:50%;
        transform: translateX(-50%);
    }
}

mixin 활용 예 ( typo-mixin 만들기 )

@mixin typo (){
    font-size: 12px;
    color: black;
    @content; // 특정 스타일을 더 추가하고싶을때 사용
}
.nav-button{
    @include typo
}

.nav-button2{
    @include typo{ // 코드 블럭 추가하고 스타일 추가하면됨
        font-weight: 700;
    }
}

@function이란?

값을 반환하기 위해 사용됨.
믹스인과의 차이점
mixin => 스타일코드 재사용
function => 값을 반환or변환하기위함

function 정의하기

@function _get-color($color){
    @return $color;
}

function 사용하기

.nav-button{
    background-color:_get-color(blue); // 함수 쓰듯 사용하면됨
}

function 활용 예 ( flex-mixin 만들기 )

$flex-map : ( // key-value map 선언
    center:center,
    sb:space-between,
    sa:space-around
);

@function get-flex-value($key){
    @return map-get($flex-map,$key); // scss 내장함수 map-get(map,key) : key의 value
}

@mixin flex ($jc:center,$ai:center){
    display: flex;
    justify-content:get-flex-value($jc) ;
    align-items: get-flex-value($ai);
}

.root{
    @include flex(sa,sb)
    @include flex
}

0개의 댓글