HTML & CSS/SASS(SCSS)
Sass/SCSS 문법 4. Maps와 @each문 사용하기
breeghty
2023. 1. 26. 20:44
1. Maps
( ) 괄호 안에 Key: Value 의 형태로 저장하여 사용한다.
Key는 고유해야 하지만 Value는 중복이 가능하다.
변수를 각각 선언하는 대신, 관련있는 변수들을 한번에 모아 maps로 만들어서 사용할 수 있다.
<body>
<section>
<h1>안녕하세요!</h1>
<h2>계묘년 새해복 많이 받으세요!</h2>
<p>이번 해는 돈 많이 버세요!</p>
</section>
</body>
//SCSS
$font-size: ("h1" : 48px, "h2" : 28px, "p":18px);
section{
h1{
font-size: map-get($font-size, "h1");
}
h2{
font-size: map-get($font-size, "h2");
}
p{
font-size: map-get($font-size, "p");
}
}
//CSS
section h1 {
font-size: 48px;
}
section h2 {
font-size: 28px;
}
section p {
font-size: 18px;
}/*# sourceMappingURL=style.css.map */
2. map 관련 내장함수
- map-get(map, key): key에 해당하는 값을 리턴하는 함수
- map-keys(map): map에 들어있는 key를 전부 리턴하는 함수
- map-values(map): map에 들어있는 values를 전부 리턴하는 함수
3. @each
each문은 lists나 maps의 각각의 요소마다 코드를 실행해서 스타일을 적용할 수 있게 한다.
@each ($변수) in (lists / maps){
//반복할 내용
}
Example
<body>
<ul>
<li class="color-circle"></li>
<li class="color-circle"></li>
<li class="color-circle"></li>
<li class="color-circle"></li>
<li class="color-circle"></li>
</ul>
</body>
//SCSS
$color-palette: yellow, teal, tomato, green, aqua;
//전역변수 리스트 선언
ul{
display: flex;
justify-content: space-between;
}
@each $color in $color-palette{
//지역변수 선언
$i: index($color-palette, $color);
//index는 lists의 내장함수이며 list 값의 인덱스를 반환한다.
.color-circle:nth-child(#{$i}){
background: $color;
width: 200px;
height: 200px;
border-radius: 50%;
list-style:none;
}
}
//CSS
ul {
display: flex;
justify-content: space-between;
}
.color-circle:nth-child(1) {
background: yellow;
width: 200px;
height: 200px;
border-radius: 50%;
list-style: none;
}
.color-circle:nth-child(2) {
background: teal;
width: 200px;
height: 200px;
border-radius: 50%;
list-style: none;
}
.color-circle:nth-child(3) {
background: tomato;
width: 200px;
height: 200px;
border-radius: 50%;
list-style: none;
}
.color-circle:nth-child(4) {
background: green;
width: 200px;
height: 200px;
border-radius: 50%;
list-style: none;
}
.color-circle:nth-child(5) {
background: aqua;
width: 200px;
height: 200px;
border-radius: 50%;
list-style: none;
}/*# sourceMappingURL=style.css.map */
참고
https://millie.page.link/fJ1WA
40 minutes Basic Sass
Front-End의 CSS를 하다 보면 어렴풋이 들려오는 Sass.Sass가 효율적인 스타일 적용에 도움이 된다 하지만, 막상 Sass를 공부하려니 주저하셨나요? S..
www.millie.co.kr