CSS-in-JS 란?

CSS-in-JS는 단어 그대로 자바스크립트 코드에서 CSS를 작성하는 방식을 말합니다. 2014년 페이스북 개발자인 Christopher Chedeau aka Vjeux가 처음 소개하였습니다.

 

Vjeux는 CSS를 작성하는 어려움을 다음과 같이 설명하였으며 CSS-in-JS로 이들 이슈를 모두 해결할 수 있다고 강조했습니다.
- Global namespace: 글로벌 공간에 선언된 이름의 명명 규칙 필요
- Dependencies: CSS간의 의존 관계를 관리
- Dead Code Elimination: 미사용 코드 검출
- Minification: 클래스 이름의 최소화
- Sharing Constants: JS와 CSS의 상태 공유
- Non-deterministic Resolution: CSS 로드 우선 순위 이슈
- Isolation: CSS와 JS의 상속에 따른 격리 필요 이슈

그리고 기존 CSS 관리의 어려움을 해결한 페이스북의 사례를 소개하였습니다. 이후 개념이 발전하면서 많은 라이브러리가 등장했습니다.

 

 

CSS-in-JS 사용률 - 출처 : https://2021.stateofcss.com/en-US/technologies/css-in-js

이 중 가장 대표적인 CSS-in-JS 라이브러리인 Styled Components를 살펴보겠습니다. Styled Components는 CSS-in-JS 스타일링을 위한 프레임워크입니다. 자바스크립트의 태그가 지정된 템플릿 리터럴과 CSS의 기능을 사용하여 구성 요소에 반응하는 스타일을 제공합니다. 장점은 다음과 같습니다. - CSS 모델을 문서 레벨이 아닌 컴포넌트 레벨로 추상화하는 모듈성 - CSS-in-JS는 JavaScript 환경을 최대한 활용 - 자바스크립트와 CSS 사이의 상수와 함수를 공유 - 현재 사용 중인 스타일만 DOM에 포함 - 짧은 길이의 유니크 한 클래스를 자동으로 생성하는 코드 경량화 단점으로는 러닝 커브(Learning Curve), 새로운 의존성 발생, 별도의 라이브러리 설치에 따른 번들 크기 증대 및 CSS-in-CSS에 비해 느린 속도 등을 들 수 있습니다. Styled Components는 스타일링을 위한 코드 사용량이 줄어들고 CSS 문법에 친화적입니다. 이는 아래 예시를 보면 알 수 있습니다.

 

 

CSS-in-CSS vs CSS-in-JS

앞서 CSS-in-CSS와 CSS-in-JS를 간단히 살펴보았지만 어떤 방식이 더 낫다고 쉽게 말할 수는 없습니다.

다만 본인의 경험에 비추어 봤을 때 작업자의 성향이나 판단이 필요한 부분이나 개발 효율성에 중점을 둔 컴포넌트 위주의 프로젝트라면 CSS-in-JS를 고려하는 것이 좋습니다. 필요한 컴포넌트 페이지의 CSS 스타일 요소만 로딩하기 때문입니다.

반면 사용자 편의에 방점을 둔 인터렉티브한 웹 프로젝트라면 랜더링 시 모든 CSS 스타일 요소를 로딩하는 CSS-in-CSS 방식을 권장하는 바입니다.

 

CSS-in-JS 장점

  • 컴포넌트로 생각하기— 더이상 스타일시트의 묶음을 유지보수 할 필요가 없습니다. CSS-in-JS는 CSS 모델을 문서 레벨이 아니라 컴포넌트 레벨로 추상화합니다(모듈성).
  • CSS-in-JS는 JavaScript 환경을 최대한 활용하여 CSS를 향상시킵니다.
  • "진정한 분리 법칙"—스코프가 있는 선택자로는 충분하지 않습니다. CSS에는 명시적으로 정의 하지 않은 경우, 부모 요소에서 자동으로 상속되는 속성이 있습니다. jss-isolate 플러그인 덕분에 JSS 규칙은 부모 요소의 속성을 상속하지 않습니다.
  • 스코프가 있는 선택자—CSS는 하나의 전역 네임스페이스만 있습니다. 복잡한 애플리케이션 내에서 선택자 충돌을 피할 수 없습니다. BEM과 같은 네이밍 컨벤션은 한 프로젝트 내에서는 도움이 되지만, 서드파티 코드를 통합할 때는 도움이 되지 않습니다. JSS는 JSON으로 표현된 것을 CSS로 컴파일 할 때, 기본적으로 고유한 이름을 생성합니다.
  • 벤더 프리픽스—생성된 CSS 규칙은 자동적으로 벤더 프리픽스가 붙어있으므로 생각할 필요가 없습니다.
  • 코드 공유—JavaScript와 CSS사이에 상수와 함수를 쉽게 공유할 수 있습니다.
  • 현재 화면에 사용중인 스타일만 DOM에 있습니다(react-jss).
  • 죽은 코드 제거
  • CSS 유닛 테스트!

 

CSS-in-JS 단점

  • 학습 곡선(Learning curve)
  • 새로운 의존성
  • 신규 팀원이 코드베이스에 적응하기 어렵게 만듭니다. 프론트엔드를 처음 접하는 사람들은 "더" 많은 것을 배워야합니다.
  • 현상 유지를 위한 도전 (꼭 단점은 아니다.)

 

원문참조 

- https://www.samsungsds.com/kr/insights/web_component.html           

- https://d0gf00t.tistory.com/22

 

반응형

 

 

https://www.surfit.io/tag/%EB%94%94%EC%9E%90%EC%9D%B8%20%EC%8B%9C%EC%8A%A4%ED%85%9C

 

#디자인 시스템 콘텐츠 - 서핏

새 탭에서 펼쳐지는 맞춤 커리어 콘텐츠. 매일 성장하고 더 멋지게 일하세요!

www.surfit.io

 

반응형

'UXUI Development > Design System' 카테고리의 다른 글

디자인시스템  (0) 2022.04.21

디자인 시스템 관리 및 유지를 위한 도구

  • 인비전 DSM(Invision DSM)
  • 피그마(Figma)
  • 액슈어(Axure)
  • 스케치(Sketch)
  • 어도비 XD(Adobe XD)
  • 제로헤이트(ZeroHeight)

 

디자인시스템 적용 예

https://developer.apple.com/design/resources/

 

Apple Design Resources

Design apps quickly by using Sketch and Photoshop templates, plug-ins, and preconfigured UI elements.

developer.apple.com

https://developer.samsung.com/design-system

 

Design System - Design | Samsung Developers

The world runs on you.

developer.samsung.com

https://developer.samsung.com/one-ui/index.html

 

https://karrisaarinen.com/posts/building-airbnb-design-system/

 

Creating the Airbnb Design System

Working in software development and design, we are often required to ship one-off solutions. Sometimes we’re working within time constraints and sometimes we just haven’t yet agreed upon a path forward. These one-off solutions aren’t inherently bad,

karrisaarinen.com

 

https://www.audi.com/ci/en/guides/user-interface/introduction.html

 

UI Introduction

Animations All animations have the dynamic character defined in the look, giving an application a lively feel. They perform functional tasks in the interface and improve the user experience: they guide the user through an application, help provide visual o

www.audi.com

 

https://baseweb.design/components/

 

https://baseweb.design/components/

 

baseweb.design

 

https://www.carbondesignsystem.com/

 

Carbon Design System

Carbon is IBM’s open source design system for products and digital experiences. With the IBM Design Language as its foundation, the system consists of working code, design tools and resources, human interface guidelines, and a vibrant community of contri

www.carbondesignsystem.com

 

https://design.socar.kr/

 

쏘카 브랜드 디자인 가이드

 

design.socar.kr

 

http://styleguide.co.kr/index.php

 

https://websrepublic.co.kr/bbs/board.php?bo_table=news&wr_id=418 

 

(주)웹스리퍼블릭

반응형웹사이트 제작전문 웹스리퍼블릭,15년 경력 전문 웹에이전시, 반응형웹, 모바일웹, 쇼핑몰 제작

websrepublic.co.kr

 

반응형

'UXUI Development > Design System' 카테고리의 다른 글

디자인시스템 2  (0) 2022.04.21

Vue에서 PDF파일 보기, 다운로드, 프린트 기능 지원하기

Install vue-pdf-app

npm i vue-pdf-app

 

Pdf.vue

// Pdf.vue
<template>
    <VuePdfApp pdf="./../resume_kangjiyeon.pdf" page-scale="100" @open="openHandler"></VuePdfApp>
</template>
<script>
import VuePdfApp from "vue-pdf-app";
export default {
  components: {
    VuePdfApp,
  },
  methods: {
    openHandler(pdfApp) {
      window._pdfApp = pdfApp;
    },
  },
};
</script>
<style scoped>
@import "https://unpkg.com/vue-pdf-app@2.0.0/dist/icons/main.css";
</style>

 

https://www.npmjs.com/package/vue-pdf-app

 

vue-pdf-app

Vue 2 pdf viewer. Latest version: 2.1.0, last published: 10 months ago. Start using vue-pdf-app in your project by running `npm i vue-pdf-app`. There are 2 other projects in the npm registry using vue-pdf-app.

www.npmjs.com


 

https://codesandbox.io/s/mqyzy8158x?file=/src/App.vue 

 

Vue PDF Download - CodeSandbox

Vue PDF Download by sakapun using html2canvas, pdfmake, vue

codesandbox.io

https://codesandbox.io/s/vue-pdf-app-external-pdfj-interaction-g5jeb?file=/src/App.vue 

 

vue-pdf-app-external-pdfj-interaction - CodeSandbox

[Vue warn]: Invalid prop: type check failed for prop "field"

codesandbox.io

https://github.com/sandanat/vue-pdf-app

 

반응형


https://ui.toast.com/weekly-pick/ko_20190430

 

앱 테마 구현 - Vue.js와 스타일드 컴포넌트로 실시간 테마 구현하기

Vue.js 프로젝트를 진행하면서 구현하기 조금 까다로웠던 기능이 있다. 완벽한 Vue 문서(Docs)만으로 바로 답을 찾을 수 없었던 부분이 있었는데, 고객 요구 사항으로 사용자 프로필에 대한 테마를

ui.toast.com

 

반응형

Typeit

https://www.typeitjs.com/

 

TypeIt

The most versatile JavaScript typewriter effect library on the planet.

www.typeitjs.com

 

Scrollout

https://scroll-out.github.io/

 

ScrollOut

Effects and CSS Vars on Scroll!

scroll-out.github.io

 

anime.js

css속성, css transform, SVG와  DOM요소의 속성, Javascript객체를 사용하여 동작하는 Javascript 애니메이션 라이브러리. 

설치 및 Import

npm install animejs --save
import anime from 'animejs/lib/anime.es.js';
<template>
  <div class="container">
  	<p class="target">target anime</p>
  </div>
</template>

export default {
	mounted() {
      this.$anime({
        targets: '.target',
        translateX: '50px',
        duration: 3000
      })
   	}
}

 

https://github.com/juliangarnier/anime

 

GitHub - juliangarnier/anime: JavaScript animation engine

JavaScript animation engine. Contribute to juliangarnier/anime development by creating an account on GitHub.

github.com


GSAP

GreenSock에서 만든 자바스크립트 애니메이션 라이브러리로 

복잡한 애니메이션을 구현하기위한 도구. 

https://greensock.com/gsap/

 

GSAP

Timeline Tip: Understanding the Position Parameter The secret to building gorgeous sequences with precise timing is understanding the super-flexible "position" parameter which controls the placement of your tweens, labels, callbacks, pauses, and even neste

greensock.com

 

반응형
// router/index.js
export default new VueRouter({
    routes: [
        {
          path: "/portfolio/blog",
          component: () => import("@/views/BlogPage.vue"),
          beforeEnter() {
            window.location.href = "https://kang-ji.tistory.com";
          },
        },
    ]
})
// views/BlogPage.vue

<template>
  <div class="blog-main">blog</div>
</template>

<script>
//import { SidebarMenu } from 'vue-sidebar-menu'

export default {
  created() {
    window.location.href = "https://kang-ji.tistory.com";
  },
};
</script>
// 컴포넌트
<template>
 <router-link tag="button" class="btn trn" to="/portfolio/blog">Blog</router-link>
</template>

외부링크로 이동

 

반응형

 

주의: mask-image는 ie 브라우저 미지원!!! 

 

mixins.scss

// mixin
@mixin svg($path, $width, $height, $color) {
	width: $width;
    height: $height;
    background-color: $color;
    -webkit-mask-image: url($path);
    mask-image: url($path);
    background-size: cover;
    -webkit-background-size: cover;
    mask-size: contain;
    -webkit-mask-position: center;
    mask-position: center;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
}

 

사용하기 (@include)

// 노랑색 배경의 검정 로고
.logo {
	width: 92px;
    height: 92px;
	background: #ffe31d;
    span {
    	@include svg('~@/assets/images/logo.svg', 78%, 21px, #000);
    }
}

 

호환성

https://caniuse.com/svg-css

 

SVG in CSS backgrounds | Can I use... Support tables for HTML5, CSS3, etc

Method of using SVG images as CSS backgrounds

caniuse.com

 

반응형

css를 사용하여 3D를 만들수 있다.

perspective 속성을 사용하여 원근감을 적용시켜준다.

perspective 속성

perspective 속성은 3D 위치 요소에 약간의 원근감을 주기 위해 z=0 평면과 사용자 사이의 거리를 결정한다.

transform 효과를 주고자하는 부모 요소에 적용.

  • perspective 에 따른 변형 호과
    • perspective가 클수록 (거리가 멀수록) 변형 효과가 적음
    • perspective가 작을수록(거리가 가까울수룩) 변형 효과가 큼
/* Keyword value */
perspective: none;

/* <length> values */
perspective: 20px;
perspective: 3.5em;

/* Global values */
perspective: inherit;
perspective: initial;
perspective: revert;
perspective: revert-layer;
perspective: unset;

 

예제

<div class="card-form">
    <div class="card">A</div>
    <div class="card">B</div>
    <div class="card">C</div>
</div>

 

 

공간에서 보는 시점에서 3D효과를 주게되면 각각의 카드가 원근감에따라 다르게 나타난다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
    perspective: 500px;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
    background: #14bb8a;
    transform: rotateY(45deg);
}

 

회전되는 요소 자체에 3D효과를 주려면 아래예제 코드처럼 카드요소의 transform안에서 perspective 속성을 부여해준다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
  	background: #14bb8a;
    transform: perspective(500px) rotateY(45deg);
}

카드 뒤집기 예제

transform-style 속성 사용 (IE미지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

 

transform-style

요소의 자식이 3D 공간에 배치되는지 또는 요소 평면에서 병합되는지 여부를 설정한다.

ie 미지원

transform-style: flat; /* 요소의 자식이 요소 자체의 평면에 있음 */
transform-style: preserve-3d; /* 요소의 자식이 3D 공간에 배치 */

 

backface-visibility

-webkit-backface-visibility: hidden;
backface-visibility: hidden;

 

최종 (IE, Safari 지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

https://developer.mozilla.org/ko/docs/Web/CSS/backface-visibility

 

backface-visibility - CSS: Cascading Style Sheets | MDN

CSS backface-visibility 속성은 요소의 뒷면이 사용자를 향할 때 보여야 하는지 지정합니다.

developer.mozilla.org

 

 

https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style

 

transform-style - CSS: Cascading Style Sheets | MDN

The transform-style CSS property sets whether children of an element are positioned in the 3D space or are flattened in the plane of the element.

developer.mozilla.org

 

반응형

1. image-rendering

이미지 랜더링 방식을 바꾼다.

원본이미지 사이즈를 그래도 사용하면 상관없지만 해당 이미지를 확대, 축소할 경우 효과를 볼 수 있다. 

크롬, 사파리 등 브라우저에서 대비를 최적화하여 이미지 랜더링을 하는데 흐린 문제를 해결해줌.

image-rendering: -moz-crisp-edges; /* firefox */
image-rendering: -o-crisp-edges; /* opera */
image-rendering: -webkit-optimize-contrast; /* chrome */
image-rendering: crisp-edges;

 

2. translateZ

z축을 0으로 적용하여 깊이감을 없앤다. 

transform: translateZ(0);

 

3. backface-visibility

뒷면을 hidden처리하여 입체감을 없앤다.

backface-visibility: hidden;

 

반응형

+ Recent posts