본문 바로가기
CSS

[CSS] CSS preprocessor : less css

by yuraming 2023. 10. 18.

less css

 

CSS preprocessor 란?

CSS 프리프로세서는 기존의 CSS를 향상+확장하기 위해 만들어진 언어로,

복잡한 스타일시트를 효율적으로 관리할 수 있도록 도와주는 도구입니다.

대표적인 CSS 프리프로세서로는 Sass, Less, Stylus 등이 있음.

 

https://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

 


 🛠️  설치 방법 

NPM
$ npm install -g less

NPM 방식으로 설치 후, less 문법으로 작성된 less 파일을 çss 문법으로 컴파일 하는 방법입니다.

//input.less -> output.css로 변환
$ lessc styles.less styles.css

 


🔍  사용법

변수 (Variables)

변수를 사용하여 스타일 속성의 값을 관리할 수 있음. (색상, 폰트 크기 등의 값을 한 번에 변경 가능하도록)

Variables
These are pretty self-explanatory:

@width: 10px;
@height: @width + 10px;

#header {
  width: @width;
  height: @height;
}

less 문법으로 작성한 변수를 스크립트에서 css 문법으로 컴파일해줌

서버에서 확인 가능 (라이브 서버), 

less 는 개발자도구에서 css 파일로 노출되지 않음 

@charset "utf-8";

@maincolor:#444444;
@titlecolor: @maincolor - #222222;
@linkcolor : @maincolor + #222222;
@mainfontsize:12px;
@titlefontsize: @mainfontsize * 2;

body{
  color:@maincolor;
  font-size: @mainfontsize;
}

h1{
  color:@titlecolor;
  font-size: @titlefontsize;
}

a{
  color:@linkcolor;
}

위 코드 아래 적용된 것 확인 가능 

 

믹스인 (Mixins)

스타일 규칙의 일부분을 재사용 가능한 코드 조각을 만들어 믹스인으로 사용 가능.

→ 반복되는 코드를 줄이고 유지보수성 향상

.bordered {
  border-top: dotted 1px black;
  border-bottom: solid 2px black;
}

nav a{
  .bordered;
}

함수처럼도 사용 가능 

.rounded-corners(@radius:5px){
  border-radius: @radius;
  padding: 5px 10px;
  background: #ccc;
}

nav h1{
  .rounded-corners(20px)
}
/* .rounded-corners 함수의 파라미터로 값 넣을 수 있음 */

 

중첩 (Nesting)

HTML 요소의 중첩 구조와 유사하게 CSS를 중첩하여 작성할 수 있음. 스타일 규칙의 가독성을 높임

#header{
  color:black;
  nav{
    font-size: 20px;
    li{
      &:last-child{
        background:silver;
      }
    }
  }
  h1 a{
    text-decoration: none;
    &:hover{ 
      text-decoration:underline;
    }
  }
}

:nth-child, :hover, :focus 등은 &(앰퍼센드):뒤에 작성 

 

 

연산 (Operations)

수학적 연산을 CSS에서 직접 수행 가능. (길이, 색상 등 계산..)

@base: 5%;
@filler: @base * 2; 
@other: @base + @filler;

@base: 2cm * 3mm;

@color: (#224488 / 2); 
background-color: #112244 + #111;

'CSS' 카테고리의 다른 글

[CSS] CSS preprocessor : SASS  (1) 2023.10.18