Sass(SCSS) Mixin

정혜지·2022년 7월 26일
0
post-thumbnail

Sass

Syntactically Awesome Style Sheets


Mixin

⭐`mixins는 스타일시트 전체에서 재사용할 CSS 선언 그룹을 정의하는 기능
스타일 시트 작성 시, 비슷하거나 동일한 스타일을 반복해서 사용해야하는 경우가 많은데 믹스인을 사용하면 사이트 전체에서 재사용할 스타일 그룹을 정의할 수 있다.


CSS 코드

h1 {
	text-align: left;
    color: white;
    background-color: teal;
    border: 1px solid red;
}
h2 {
	text-align: center;
    color: white;
    background-color: teal;
    border: 1px solid red;
}
p {
	text-align: right;
    color: white;
    background-color: teal;
    border: 1px solid red;
}



@mixin 정의

@mixin [mixin-name] {재사용할 스타일}
믹스인을 만들때는 @mixin 지시자를 사용


ex) my-font라는 mixin 만들기

@mixin my-font {
	font-family: sans-serif;
    font-size: 32px;
    font-style: normal;
    font-weight:600;
    color: orange;
}

@mixin [mixin name] { }
블록 안에 재사용할 스타일 지정



Mixin 호출

@include [mixin-name]

스인에 정의된 스타일을 넣고자 하는 모든 곳에 @include 지시자를 사용하여 해당 믹스인 호출할 수 있다.

h1 {
	@include my-font;
}

p {
	@include my-font;
}


믹스인 인자

sass의 믹스인은 인자를 취할 수 있다.
믹스인 정의 시에 괄호와 함께 변수를 추가하면 인자가 정의된다.
믹스인 호출 시에 인자를 전달하고 싶다면 믹스인 이름 옆에 괄호와 함께 속성값 추가하면 된다.


SCSS 코드

@mixin my-font($font-color) {
    font-size: 18px;
    font-weight: 900;
    color: $font-color;
}
h1{
	@include my-font(red)
}

p {
	@include my-font(blue)
}

⭐ 인자를 더 넣고 싶다면, 변수 옆에 쉼표를 쓰고 추가


CSS 컴파일 코드

h1 {
	font-size: 18px;
    font-weight: 900;
    color: red;
}
p {
	font-size: 18px;
    font-weight: 900;
    color: blue;
}



믹스인 인자 기본값

믹스인 인자에 기본값을 정의해두면 인자 전달 여부에 따라 선택적으로 스타일이 결정된다.
기본값은 인자로 변수 옆에 ':'을 쓰고 속성값을 써서 정의한다.


SCSS 코드

@mixin my-font($font-color, $bg-color: yellow) {
	font-size: 18px;
    font-weight: 900;
    color: $font-color
    background-color: $bg-colorl
}

믹스인을 호출할때 $bg-color에 속성값을 전달하지 않으면 배경색은 기본값인 yellow로 결정된다.






실습

@mixin box-style($bg-color:skyblue, $font-color:green){
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: $bg-color;
  color: $font-color;
}


.one {
  @include box-style($bg-color: lightcoral)
}
.two {
  @include box-style(purple, yellow)
}

profile
오히려 좋아

0개의 댓글