responsive mixin

YEONGHUN KO·2022년 1월 6일
1

CSS/SCSS - BASICS

목록 보기
5/12
post-thumbnail

1. responsive mixin

이번엔 화면에 크기에 따라 효과가 적용되는 mixin을 만들어볼려고 한다. responsive mixin은 @content 함수를 통해 함수 내용을 styles.scss에서 설정할 수 있다. 그럼 먼저 html 을 만들어주자. 화면 크기에 따라 HELLO의 색깔이 바뀔것이다.

<!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>
    <h1>Hell3o</h1>
  </body>
</html>

그리고 _mixins.scss 파일을 만들어주자. 그리고 안에 변수를 설정하고 media query로 화면의 최소, 최대크기를 설정한다. 그리고 @content를 적어준다. 말그대로 media query의 효과는 함수가 적용될때 외부에서 설정한 값에 따라 유연하게 반응한다는 것이다. 말로는 잘 이해가 가지 않는다. 다음 코드를 통해 더 자세히 살펴보자.

$minIphone: 400px;
$maxIphone: 700px;
$minTablet: 900px;
$maxTablet: 1100px;

@mixin responsive($device) {
  @if $device == "iphone" {
    @media screen and (max-width: $maxIphone) and (min-width: $minIphone) {
      @content;
      // 즉 최소넓이가  400px 그리고 최대 700ox 일때 효과가 발동되는 데
      // 그 효과는 styles.scss 에 적어준대로다.(@content때문에 가능한 기능이다.)
    }
  } @else if $device == "tablet" {
    @media screen and (max-width: $maxTablet) and (min-width: $minTablet) {
      @content;
    }
  }
}

아래 처럼 mixins 를 import 하고 @include 를 이용해 마찬가지로 함수를 호출한다. 그리고 인자를 넣어주고 적용될 효과를 적어준다. 이때 지정한 효과가 @content가 되는 것이다.

@import "_mixins";

h1 {
  @include responsive("iphone") {
    color: yellowgreen;
  }
  @include responsive("tablet") {
    color: peru;
  }
}
// responsive 함수안에 있는 @content 때문에 h1 태그에 적는 족족 responsive와 연동되어 함께 효과가 나타난다.

https://raspy-emery-991.notion.site/4-TIL-SCSS-4d98546337a94e8198a43b510ffb89dd

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글