Home SCSS - mixin
Post
Cancel

SCSS - mixin

1. MIXIN

MIXIN를 이번에 배워보자. MIXIN는 함수와 모양과 기능이 비슷하다. 그리고 IF/ELSE 와 같은 조건문도 넣을 수 있다. 역시나 html 을 먼저 만들어주자. 홀수번째 google 은 파란색 짝수번째에 있는 google은 빨간색으로 설정해주려 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="dist/css/reset.css" />
    <link rel="stylesheet" href="dist/css/styles.css" />
    <title>(S)CSS Masterclass</title>
  </head>
  <body>
    <a href="#">Google</a>
    <a href="#">Google</a>
    <a href="#">Google</a>
    <a href="#">Google</a>
    <a href="#">Google</a>
    <!-- google 이라는 링크를 5개 만들고 싶다고 하면 a*5{google} 이라고 하면 됨 -->
  </body>
</html>

그리고 _minxins.scss 란 파일을 만들어주자.(참고로 import하려는 파일은 styles.scss 와 같은 폴더안에 있어야 한다.) mixin을 정의할때는 @ 기호를 사용하고 함수이름을 설정한다. 보면 알겠지만 인자까지 pass할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@mixin link($color) {
  text-decoration: none;
  display: block;
  color: $color;
}
@mixin awesome($word) {
  text-decoration: none;
  display: block;
  @if $word == "odd" {
    color: blue;
  } @else {
    color: red;
  }
} //엄청나지 않나?? 파이썬 함수 만들때 처럼 인자설정은 물론, if/else 문까지 쓸수 있다.

그리고 _minxins를 import 한다음 scss 코드를 적어주면 된다. include 를 이용해서 함수를 호출한다.

1
2
3
4
5
6
7
8
9
10
@import "_minxins";
a {
  margin-bottom: 10px;
  &:nth-child(odd) {
    @include awesome("odd");
  }
  &:nth-child(even) {
    @include awesome("even");
  }
} //파이썬 처럼 minxins 안에 있는 함수를 적용하였다. 이때 include 를 사용한다.

결과

그럼 아래와 같이 짜잔하고 나타난다.

mixin

CSS로 처리할 수 있는것은 최대한 CSS로 처리하자. JS에 넘겨주면 그게 다 성능에 영향을 끼친다.

This post is licensed under CC BY 4.0 by the author.