[SCSS] 조건문 if, 다중조건문 @if, @else if, @else

문지은·2023년 8월 27일
0

SCSS

목록 보기
10/11
post-thumbnail

조건문 if

  • SCSS에서 조건문은 자바스크립트와 마찬가지로 조건의 값은 참(true), 거짓(false) 2가지로 표현되며, 둘 중에 조건에 따라 1개를 표현한다.
if(조건, 참일 때 표현식, 거짓일 때 표현식)

width 크기에 따라 다른 배경색을 나타내도록 디자인을 만들어보자.

index.html

<div class="frame">
  <div class="item1">item1</div>
  <div class="item2">item2</div>
</div>

style.scss

.frame div {
  height: 100px;
	border: 5px solid black;
	margin: 10px;
	padding: 10px;
	box-sizing: border-box;
}

$width-case1 : 500px;
$width-case2 : 250px;

.item1 {
	width: $width-case1;
	background-color: if($width-case1 > 600px, crimson, yellow);
}

.item2 {
	width: $width-case2;
	background-color: if($width-case2 > 300px, royalblue, tomato);
}

style.css

.frame div {
  height: 100px;
  border: 5px solid black;
  margin: 10px;
  padding: 10px;
  box-sizing: border-box;
}

.item1 {
  width: 500px;
  background-color: yellow;
}

.item2 {
  width: 250px;
  background-color: tomato;
}

다중 조건문 @if, @else if, @else

  • 자바스크립트처럼 조건이 여러 개일 때 @if, @else if, @else로 조건별로 값은 참(true), 거짓(false)을 판단해 참일 경우를 표현
  • 조건이 늘어날 때 @else if를 추가
  • 조건을 감싸는 괄호는 생략 가능
@if(조건 1) {
  // 조건 1이 참(true)일 때 표현식
}
@else if(조건 2) {
  // 조건 2rk 참(true)일 때 표현식
}
@else {
  // 모두 거짓(false)일 때 표현식
}

다중 조건문을 활용하여 박스 width에 따라 다른 배경색을 나타내도록 디자인해보자.

index.html

<div class="frame">
  <div class="item">item</div>
</div>

style.scss

@mixin item-box {
	border: 5px solid black;
	margin: 10px;
	padding: 10px;
	text-align: center;
	box-sizing: border-box;
}

$width: 300px;

.item {
	@include item-box;
	width: $width;
	@if($width >= 300) {
		background-color: crimson;
	}
	@else if($width < 300) {
		background-color: royalblue;
	}
}

style.css

.item {
  border: 5px solid black;
  margin: 10px;
  padding: 10px;
  text-align: center;
  box-sizing: border-box;
  width: 300px;
  background-color: crimson;
}
  • width: 300px 이상인 경우
  • width: 300px 미만인 경우
profile
코드로 꿈을 펼치는 개발자의 이야기, 노력과 열정이 가득한 곳 🌈

0개의 댓글