Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-15 13:20
관리 메뉴

nomad-programmer

[Programming/HTML|CSS] Less 스타일시트 엔진 본문

Programming/HTML|CSS

[Programming/HTML|CSS] Less 스타일시트 엔진

scii 2020. 12. 21. 18:03

스타일시트를 더 쉽게 사용하고자 다양한 스타일시트 엔진들이 등장했다. 스타일시트 엔진은 특정한 형태의 스타일시트를 CSS 스타일시트로 변경해주는 변환 엔진(컴파일러) 이다. 일반적으로 많은 사용하는 스타일시트 엔진으로는 Sass 스타일시트 엔진과 Less 스타일시트 엔진등이 있다.

공식 홈페이지

lesscss.org/

 

Getting started | Less.js

Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript tool that converts your Less styles to CSS styles. Because Less looks ju

lesscss.org

Github

github.com/less/less.js

 

less/less.js

Less. The dynamic stylesheet language. Contribute to less/less.js development by creating an account on GitHub.

github.com

NOTE : 파일을 저장할 때 확장자를 .less로 지정하여 만들면 Less 스타일 시트를 사용할 수 있다. 그리고 반드시 less 파일과 HTML 파일이 같은 도메인에 있어야 한다.

다음은 less로 작성한 스타일시트다.

/* less 스타일시트 */

header {
  width: 800px;
  margin: 0px auto;

  hgroup {
    h1 {
      color: red;
    }
    h2 {
      color: blue;
    }
  }

  nav {
    ul {
      overflow: hidden;
    }
    li {
      float: left;
    }
  }
}

이것을 css로 컴파일하면 다음과 같은 스타일시트가 생성된다.

/* 컴파일된 css 스타일시트 */

header {
  width: 800px;
  margin: 0px auto;
}
header hgroup h1 {
  color: red;
}
header hgroup h2 {
  color: blue;
}
header nav ul {
  overflow: hidden;
}
header nav li {
  float: left;
}

이렇게 특정한 형태의 스타일시트를 일반 스타일시트로 변환해주는 것을 스타일시트 엔진이라고 부른다.


Less 컴파일러

HTML 페이지에 Less 자바스크립트 파일을 추가하면 Less 스타일시트를 변환할 수 있다. 하지만 자바스크립트 파일을 사용자에게 전달하는 것은 트래픽 낭비이다. 또한 Less 스타일시트를 변환하는 시간조차 사용자는 불만을 품을 수 있다.

따라서 Less 자바스크립트 파일을 추가하지 않고 Less 스타일시트를 변환하는 방법을 알아보자. 

우선 가장 쉽게 사용할 수 있는 Less 스타일시트 컴파일러는 온라인 Less 컴파일러이다.

www.winless.org/

 

WinLess - Windows GUI for less.js

Online LESS Compiler This Online LESS Compiler can help you to learn LESS. You can go through the examples below or try your own LESS code. The examples are based on the official LESS documentation

www.winless.org

온라인 Less 컴파일러

온라인 Less 컴파일러의 웹 사이트에서 왼쪽 입력 화면에 Less 스타일시트를 입력하면 자동으로 스타일시트로 변환해준다.

만약 인터넷이 되지 않는 상황에서 Less 스타일시트를 변환해야 한다면 SimpLess 컴파일러를 설치해 사용한다. SimpLess 컴파일러는 모든 운영체제를 지원한다.

github.com/Paratron/SimpLESS

 

Paratron/SimpLESS

A simple LESS compiler for Windows and mac. Contribute to Paratron/SimpLESS development by creating an account on GitHub.

github.com

개발 환경과 통합해서 사용할 수 있는 Less 컴파일러도 존재한다. 예를 들어 웹 매트릭스 개발 환경을 사용하는 경우에는 OrangeBits 컴파일러가 기본으로 내장되어 쉽게 변환할 수 있다.


Less 스타일시트 사용

변수

Less 스타일시트는 변수를 만들 수 있다. 변수를 만들 때는 @ 기호를 사용하며 스타일시트에서 사용하는 모든 단위를 저장할 수 있다.

@color: #e3e3e3;
@defaultFontSize: 16px;

body {
  color: @color;
  font-size: @defaultFontSize;
}

이것을 실행하면 다음과 같이 변환된다.

body {
  color: #e3e3e3;
  font-size: 16px;
}

모든 색상을 이렇게 변수로 지정해 놓으면 페이지의 전체 테마를 단숨에 바꿀 수 있다. 


연산

Less 스타일시트는 연산을 수행할 수 있다. 예를 들어 다음과 같은 코드를 보자. 뺄셈과 곱셈을 사용해 width 속성값을 손쉽게 적용하였다.

@margin: 10px;
@padding: 10px;
@width: 200px;

div {
  width: @width - (@padding * 2);
  padding: @padding;
  margin: @margin;
}

이것을 컴파일하면 다음과 같은 코드로 변환된다.

div {
  width: 180px;
  padding: 10px;
  margin: 10px;
}

위에서 사용한 width 속성값을 적용하는 방법은 물론 다양한 곳에 활용할 수 있다.


내장 선택자

Less 스타일시트는 불록 안에 블록을 포함할 수 있다. 이때 블록 내부에서는 & 선택자를 사용할 수 있다.

& 선택자는 블록 내부에서 자신을 뜻하는 선택자이다.

예를 들어 다음과 같은 코드를 사용하면 a 태그의 상태 선택자를 블록 내부에 넣을 수 있다.

a {
  &:hover {
  }
  
  &:active {
  }
}

정말 깔끔하고 알기 쉽게 스타일시트를 입력할 수 있다.

div {
  background: black;
  &:hover {
    background: white;
  }

  a {
    background: red;
    color: white;
    &:hover {
      background: blue;
    }
    &:active {
      background: green;
    }
  }
}

이것을 컴파일하면 다음과 같은 코드로 변환된다.

div {
  background: black;
}
div:hover {
  background: white;
}
div a {
  background: red;
  color: white;
}
div a:hover {
  background: blue;
}
div a:active {
  background: green;
}

내장 함수

Less 스타일시트는 개발자의 편의를 위해 몇 가지 함수를 제공한다. 가장 쉽게 사용할 수 있는 내장 함수는 색상과 관련된 내장 함수이다. 

색상 관련 내장 함수

함수 이름 설명
lighten (색상 단위, 퍼센트 단위) 색상을 밝게 만든다.
darken (색상 단위, 퍼센트 단위) 색상을 어둡게 만든다.
saturate (색상 단위, 퍼센트 단위) 색을 두드러지게 만든다.
desaturate (색상 단위, 퍼센트 단위) 색을 두르러지지 않게 만든다.
fadein (색상 단위, 퍼센트 단위) 색상을 투명하지 않게 만든다.
fadeout (색상 단위, 퍼센트 단위) 색상을 투명하게 만든다.
fade (색상 단위, 퍼센트 단위) 색상을 반투명하게 만든다. (50%)
spin (색상 단위, 퍼센트 단위) 색상 속성을 변경한다.
mix (색상 단위, 퍼센트 단위) 색상을 섞는다.
@color: #ff0000;

div {
  height: 10px;
}

div:nth-child(1) {
  background: darken(@color, 0%);
}
div:nth-child(2) {
  background: darken(@color, 10%);
}
div:nth-child(3) {
  background: darken(@color, 20%);
}
div:nth-child(4) {
  background: darken(@color, 30%);
}
div:nth-child(5) {
  background: darken(@color, 40%);
}
div:nth-child(6) {
  background: darken(@color, 50%);
}

darken() 함수는 특정한 색상을 더 어둡게 표현할 수 있게 만들어주는 함수이다.

다음은 위의 코드를 변환한 코드이다.

div {
  height: 10px;
}
div:nth-child(1) {
  background: #ff0000;
}
div:nth-child(2) {
  background: #cc0000;
}
div:nth-child(3) {
  background: #990000;
}
div:nth-child(4) {
  background: #660000;
}
div:nth-child(5) {
  background: #330000;
}
div:nth-child(6) {
  background: #000000;
}

dark() 함수 이외의 다른 색상 관련 내장 함수도 쉽게 사용할 수 있다. 

색상 속성 추출 내장 함수

함수 이름 설명
hue (색상 단위) 색상의 Hue 속성을 추출한다.
saturation (색상 단위) 색상의 Saturation 속성을 추출한다.
lightness (색상 단위) 색상의 Lightness 속성을 추출한다.
alpha (색상 단위) 색상의 Alpha 속성을 추출한다.

다음의 코드는 @color 변수에 무엇을 지정하냐에 따라 색상 조합 전체가 바뀐다.

@color: #ff0000;
@hue: hue(@color);
@saturation: saturation(@color);
@lightness: lightness(@color);

div {
  height: 5px;
}

div:nth-child(1) {
  background: hsl(@hue, @saturation, @lightness);
}
div:nth-child(2) {
  background: hsl(@hue+10, @saturation, @lightness);
}
div:nth-child(3) {
  background: hsl(@hue+20, @saturation, @lightness);
}
div:nth-child(4) {
  background: hsl(@hue+30, @saturation, @lightness);
}
// ...
// 참고로Less 스타일시트는 이렇게 한 줄 주석도 사용할 수 있다.
// ...
div:nth-child(24) {
  background: hsl(@hue+230, @saturation, @lightness);
}
div:nth-child(25) {
  background: hsl(@hue+240, @saturation, @lightness);
}

위의 코드를 변환하면 다음의 코드가 된다.

div {
  height: 5px;
}
div:nth-child(1) {
  background: #ff0000;
}
div:nth-child(2) {
  background: #ff2b00;
}
div:nth-child(3) {
  background: #ff5500;
}
div:nth-child(4) {
  background: #ff8000;
}
div:nth-child(24) {
  background: #002bff;
}
div:nth-child(25) {
  background: #0000ff;
}
색상 관련 함수를 사용하면 웹 페이지의 전체 테마를 손쉽게 변경할 수 있다. 유용하게 사용할 수 있는 함수이다.

그리고 Less 스타일시트는 다음과 같이 수학 함수도 제공한다.

함수 이름 설명
round (숫자) 숫자를 반올림한다.
ceil (숫자) 숫자를 올림한다.
floor (숫자) 숫자를 내림한다.
percentage (숫자) 숫자를 퍼센트 단위로 변경한다.

믹스인 (사용자 정의 함수)

Less 스타일시트가 기본으로 내장하고 있는 함수도 유용하지만 본인이 직접 함수를 만들 수도 있다. 이렇게 개발자가 스스로 만든 함수를 Less 스타일시트는 "믹스인(Mixin)" 이라고 부른다.

믹스인은 '.이름( ) { }' 형태로 선언하고 .이름() 형태로 실행한다. 다음은 믹스인을 선언하고 실행한다. 믹스인 블록 내부에는 적용할 스타일을 입력한다.

// 믹스인 선언
.button() {
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 5px;
}

div {
  background: red;

  // 믹스인을 실행한다.
  .button();
}

위의 코드를 변환하면 다음과 같은 코드가 된다. 믹스인 내부의 스타일이 그대로 사용되는 것을 확인할 수 있다.

div {
  background: red;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 5px;
}

믹스인의 괄호 안에는 매개변수를 입력할 수 있다. 다음의 코드처럼 linearGradient() 믹스인을 만들면 어떠한 경우에서나 쉽게 그레디언트를 사용할 수 있다.

.linearGradient(@start, @end) {
  background: @start;
  background: linear-gradient(top, @start 0%, @end 100%);
}

믹스인을 반복해서 입력해야 하는 스타일을 사용할 때 정말 편리하다. 다음은 예제는 믹스인을 이용하여 버튼 3개를 만드는 예제이다.

.linearGradient(@start, @end) {
  background: @start;
  background: linear-gradient(top, @start 0%, @end 100%);
}

.button(@width, @height, @radius) {
  width: @width;
  height: @height;
  line-height: @height;
  text-align: center;
  border-radius: @radius;
}

* {
  margin: 0px;
  padding: 0px;
}

div {
  margin: 10px;
  float: left;

  &:nth-child(1) {
    .linearGradient(#0058ff, #002389);
    .button(200px, 100px, 10px);
  }

  &:nth-child(2) {
    .linearGradient(#0058ff + #cc0000, #002389 + #cc0000);
    .button(200px, 100px, 10px);
  }

  &:nth-child(3) {
    .linearGradient(#0058ff + #ff0000, #002389 + #ff0000);
    .button(200px, 100px, 10px);
  }
}

코드를 실행하면 다음과 같이 출력한다.

믹스인 복합 사용

다음은 위의 less 코드를 변환한 결과이다. 믹스인이 귀찮은 일을 얼마나 많이 줄여주는지 알 수 있다.

* {
  margin: 0px;
  padding: 0px;
}
div {
  margin: 10px;
  float: left;
}
div:nth-child(1) {
  background: #0058ff;
  background: linear-gradient(top, #0058ff 0%, #002389 100%);
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 10px;
}
div:nth-child(2) {
  background: #cc58ff;
  background: linear-gradient(top, #cc58ff 0%, #cc2389 100%);
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 10px;
}
div:nth-child(3) {
  background: #ff58ff;
  background: linear-gradient(top, #ff58ff 0%, #ff2389 100%);
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 10px;
}

게다가 믹스인은 유용한 몇 가지만 지정해놓으면 코드 재사용을 할 수 있다. 하지만 내가 만든 믹스인을 한참 지난 후 재사용할 때는 물론이고, 다른 사람이 만든 믹스인을 사용할 때는 매개변수에 다른 형식의 값을 넣는 실수를 할 수 있다.

이러한 실수를 방지하고자 Less 스타일시트는 다음의 코드처럼 자료형을 확인할 수 있는 코드를 사용한다. 

믹스인 선언 뒤에 when 키워드를 붙여 사용한다.
.linearGradient(@start, @end) when (iscolor(@start)) and (iscolor(@end)) {
  background: @start;
  background: linear-gradient(top, @start 0%, @end 100%);
}

자료형 확인 내장 함수

함수 이름 설명
iscolor (변수) 변수가 색상 단위인지 확인
isnumber (변수) 변수가 숫자 단위인지 확인
isstring (변수) 변수가 문자열 단위인지 확인
iskeyword (변수) 변수가 키워드인지 확인
isurl (변수) 변수가 URL 단위인지 확인
ispixel (변수) 변수가 픽셀 단위인지 확인
ispercentage (변수) 변수가 퍼센트 단위인지 확인
isem (변수) 변수가 배수 단위인지 확인

when 키워드는 비교 연산자를 사용해 다른 조건도 확인할 수 있다. 예를 들어 다음의 코드는 믹스인의 이름이 같지만 when 키워드를 사용해 조건을 분리하므로 정상 작동한다.

.max(@a, @b) when (@a > @b) {
  width: @a;
}
.max(@a, @b) when (@a < @b) {
  width: @b;
}

.min(@a, @b) when (@a > @b) {
  width: @b;
}
.min(@a, @b) when (@a < @b) {
  width: @a;
}

Less 스타일시트 믹스인은 매개 변수에 디폴트 값을 지정할 수 있다.

.button(@width: 200px, @height: 100px, @radius: 10px)
  when
  (ispixel(@width))
  and
  (ispixcel(@height))
  and
  (ispixel(@radius)) {
  width: @width;
  height: @height;
  line-height: @height;
  text-align: center;
  border-radius: @radius;
}

Node.js를 사용한 서버에서의 Less 스타일시트 컴파일 방법

이 방법이 온라인 Less 컴파일러를 이용한 방법보다 훨씬 실전적인 방법이라 할 수 있다. 

서버를 사용한 변환

Node.js를 사용해 서버에서 Less 스타일시트를 변환하는 방법을 알아보자. 

/* LessStyleSheet.less 파일 */

* {
  margin: 0px;
  padding: 0px;
}

h1 {
  font-family: Arial, Helvetica, sans-serif;
}

정적 파일 변환

Node.js가 설치되어 있다면 다음 명령어를 사용하여 less 모듈을 전역 위치에 설치할 수 있다.

$ npm install -g less

less 모듈을 전역 위치에 설치하면 lessc 명령어를 사용해 Less 스타일시트를 변환할 수 있다. 다음 명령어를 사용해 Less 스타일시트를 CSS 스타일시트로 변경한다.

$ lessc LessStyleSheet.less > StyleSheet.css

변환이 완료되면 다음과 같은 스타일시트가 생성된다.

$ ls
LessStyleSheet.less LessStyleSheet.css

스타일시트를 변환할 때 다음과 같이 '-x' 옵션을 사용하면 용량을 최소화한 스타일시트를 얻을 수 있다.

$ less -x LessSTyleSheet.less > StyleSheet.css

용량을 최소화한 스타일시트는 다음과 같이 공백이 삭제된 형태이다.

*{margin:0px;padding:0px}h1{font-family:Arial,Helvetica,sans-serif

동적 파일 변환

동적으로 Less 스타일시트를 변환할 때는 Node.js의 less 모듈을 사용한다. less 모듈은 다음과 같은 명령어를 사용해 설치한다.

$ npm install less

Server.js 파일에는 다음 코드를 입력한다. less 모듈 render() 메서드의 첫 번째 매개변수에 스타일시트 문자열을 넣기만 하면 되므로 쉽게 사용할 수 있다.

// 모듈을 추출한다.
let http = require('http')
let fs = require('fs');
let less = require('less');

// 서버를 생성 및 실행한다.
http.createServer(function(request, response){
    // 파일을 읽는다.
    fs.readFile('LessStyleSheet.less', 'utf8', function(error, data){
        // 스타일시트를 변환한다.
        less.render(data, function(error, style){
            // 응답한다.
            response.writeHead(200, {'Content-Type': 'text/css'});
            response.end(style);
        });
    });
}).listen(52273, function(){
    console.log('Server Running at http://127.0.0.1:52273');
});

본인은 Docker를 이용하여 Node.js 서버를 돌렸다. 그 명령은 다음과 같다.

$ docker container run -itd --name nodejs --rm -p 52273:52273 -v ~/Documents/workspace/web:/root/test node /bin/bash
$ docker container attach nodejs

root@abcd:~/test# npm install less
root@abcd:~/test# node Server.js
Comments