SCSS 기초

훈나무·2022년 11월 15일
1

scss

목록 보기
1/2
post-thumbnail

scss란

vue 로 프로젝트를 진행중인데, 기본적으로 scss 를 내장하고 있어서 공부하게 되었습니다.

css와의 차별점

style을 작성하는데 css만으로는 불편한 점이 많습니다. 그중 가장 불편하다고 느끼는 점은 아무래도 재사용이 힘들다는 점입니다.
scss는 이러한 단점을 많은 부분 보안했습니다.


변수 (variable)

scss 에서는 $ 를 통해서 변수를 지정하고 사용할 수 있습니다.

$red: #d0d;
.danger {
  background-color: $red;
}

데이터 종류

scss 에서 사용할 수 있는 데이터의 종류는 다음과 같다.

$number: 1; //.5,100x,1rem
$string : bold; // relative, "../images/a.png"
$color : red; // blue,#FFFF00,regb(0,0,0,0.1)
$boolean : true; //true, false
$null : null;
$list : orange,royalblue,yellow;
$map:(
	o:orange,
    r:royalblue,
    y:yellow
); //객체

//객체 사용법
div{
  background-color: map-get($map, o);
}

중첩

다음과 같은 html 에서 style을 주기 위해서 scss에서는 다음과 같이 가능합니다

<section >
  <div>
  	<form>
    	<input type="text"/>
  	</form>
  </div>
</section>

section{
	$blue: #1b7ced;
	div{
    	display:flex;
        flex-direction:column;
    	form{
        	padding:1rem;
        	input{
            	color:blue;
            	width:30rem;
            }
        }
    }
}

산술연산

scss에서는 css에서는 불가능한 +,-,*,/ 와같은 산술연산이 가능합니다.

단 나누기는 괄호로 묶어줘야 합니다

$size :30px;
div{
	width:20px + 20px;
    height:40px - 10px;
    font-size:$size * 2;
    margin:$size/2;
}
span{
	margin : 30px /2;
    padding: (30px/2);
}

mixin

css 를 함수처럼 사용하는 기능입니다. @mixin 으로 생성해주고, @include 로 호출합니다.
괄호안에 변수를 줄 수 있고, default 값을 지정해 줄 수 있습니다.

$size :30px;
@mixin center{
	display:flex;
    justify-content:center;
    align-items:center;
}
@mixin box($size:80px){
	width: $size;
    height: $size;
    background-color:tomato;
}
.container{
	@include center;
}
.box{
	@include box(100px);
}
.box2{
	@include box;
}

반복문

기존의 css 에서는 불가능 했던 반복문이 scss변수가 있기 때문에 에서는 가능하다.

@for $i from 1 through 10{
	.box:nth-child(#{$i}){
		width:100px * $i;
	}
}

반환되는 css

.box:nth-child(1){
	width:100px;
}
.box:nth-child(2){
	width:200px;
}

함수

mixin과의 차이점은 mixin 은 style markup 을 반환하지만,
function 은 @return 를 통하여 값 을 반환합니다.
Function을 선언 할 때는, @function 를 사용합니다.

@function makelongshadow($color) {
  $val: 0px 0px $color;
  @for $i from 1 through 200 {
    $val: #{$val}, #{$i}px #{$i}px #{$color};
  }
  @return $val;
}
/*---------------------------------*/
@mixin longshadow($color) {
  text-shadow: makelongshadow($color);
}
/*---------------------------------*/
h1 {
    @include longshadow(darken($color, 5% ));
}

함수는 @include 같은 별도의 지시어 없이 사용하기 때문에 내가 지정한 함수와 내장 함수(Built-in Functions)의 이름이 충돌할 수 있습니다.
따라서 내가 지정한 함수에는 별도의 접두어를 붙여주는 것이 좋습니다.

profile
프론트엔드 개발자 입니다

0개의 댓글