[ Tailwind CSS ] 1.핵심 컨셉

angie·2023년 1월 6일
0

HTML&CSS

목록 보기
8/11

핵심 컨셉

1. Utility-First Fundamentals

<div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4">
  <div class="shrink-0">
    <img class="h-12 w-12" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div>
    <div class="text-xl font-medium text-black">ChitChat</div>
    <p class="text-slate-500">You have a new message!</p>
  </div>
</div>

Tailwind CSS 내부에 이미 정의된 유틸리티 클래스를 사용하여 빠르게 스타일링을 할 수 있다.

유틸리티 클래스의 장점

  1. CSS를 작성할 필요가 없다.
  2. 클래스명에 대한 고민할 필요가 없다.
  3. 유지 보수가 쉽다.



2. Hover, Focus 등의 요소 스타일링

hover, focus와 같은 Pseudo-class를 의미하는 수식자를 유틸리티 클래스 이름의 앞에 추가하여 사용할 수 있다.

<button class="bg-sky-500 hover:bg-sky-700 ...">   Save changes </button>

기존 CSS의 fist-child, last-child, required, invalid, disabled 등등 다양한 상태에 대한 수식자를 제공하고 있다. 이는 공식문서 참조 LINK



3. 반응형 스타일

일반적인 클래스명에 md:와 같은 수식자를 추가하여 빠르게 적용할 수 있다.

Breakpoint PrefixMinimum WidthCSS
sm640px@media (min-width: 640px) { ... }
md768px@media (min-width: 768px) { ... }
lg1024px@media (min-width: 1024px) { ... }
xl1280px@media (min-width: 1280px) { ... }
2xl1536px@media (min-width: 1536px) { ... }

mobile first로 작업

Tailwind는 모바일 우선 중단점을 사용한다고 한다. prefix가 없는 유틸리티 클래스로 모바일 스크린을 타켓으로 스타일링한 다음, 그것보다 큰 중단점에 대한 스타일링을 쌓아간다. (오버라이드)

<!-- This will center text on mobile, and left align it on screens 640px and wider -->
<div class="text-center sm:text-left"></div>

breakpoint 커스터마이징

tailwind.config.js파일을 통해 중단점을 커스터마이징할 수 있다. 자세한 내용은 공식문서 참조 (Link)



4. 다크 모드

Tailwind의 강력한 기능 중 하나라고 생각한다. 다크모드에 대한 스타일링을 바로 지정할 수 있는 prefix를 제공한다.

<div class="bg-white dark:bg-slate-800 rounded-lg px-6 py-8 ring-1 ring-slate-900/5 shadow-xl">
  <div>
    <span class="inline-flex items-center justify-center p-2 bg-indigo-500 rounded-md shadow-lg">
      <svg class="h-6 w-6 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true"><!-- ... --></svg>
    </span>
  </div>
  <h3 class="text-slate-900 dark:text-white mt-5 text-base font-medium tracking-tight">Writes Upside-Down</h3>
  <p class="text-slate-500 dark:text-slate-400 mt-2 text-sm">The Zero Gravity Pen can be used to write in any orientation, including upside-down. It even works in outer space.</p>
</div>

다크 모드 토글하는 법

운영체제 환경설정에 의존하지 않고 수동으로 다크모드 전환을 지원하는 방법이다. localstorage에 "theme" 정보를 "light" 혹은 "dark"로 저장해놓고, 그 값에 따라 html태그에 클래스를 토글하여 추가한다.

// tailwind.config.js

module.exports = {
  darkMode: 'class',
  // ...
}
<!-- Dark mode not enabled -->
<html>
<body>
  <!-- Will be white -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->
  </div>
</body>
</html>

<!-- Dark mode enabled -->
<html class="dark">
<body>
  <!-- Will be black -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->
  </div>
</body>
</html>

** 리액트에서 다크모드로 바꾸는 컴포넌트 예시 참고 (Link)



5. 스타일 재사용

1) 컴포넌트화 하기

일부 스타일을 재사용해야 하는 경우 React, Svelte 또는 Vue와 같은 프론트엔드 프레임워크를 사용하여 재사용할 스타일을 컴포넌트화하여 재사용할 수 있다.

vue.js 예시

<template>
  <div>
    <img class="rounded" :src="img" :alt="imgAlt">
    <div class="mt-2">
      <div>
        <div class="text-xs text-slate-600 uppercase font-bold tracking-wider">{{ eyebrow }}</div>
        <div class="font-bold text-slate-700 leading-snug">
          <a :href="url" class="hover:underline">{{ title }}</a>
        </div>
        <div class="mt-2 text-sm text-slate-600">{{ pricing }}</div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    props: ['img', 'imgAlt', 'eyebrow', 'title', 'pricing', 'url']
  }
</script>

jsx 예시

function Notification({ imageUrl, imageAlt, title, message }) {
  return (
    <div className="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-md flex items-center space-x-4">
      <div className="shrink-0">
        <img className="h-12 w-12" src={imageUrl.src} alt={imageAlt}>
      </div>
      <div>
        <div className="text-xl font-medium text-black">{title}</div>
        <p className="text-slate-500">{message}</p>
      </div>
    </div>
  )
}

2) @apply를 사용한 클래스 추출

버튼과 같은 작은 요소들은 컴포넌트로 만들어 재사용하기에는 CSS 클래스를 작성하는 것에 비해 과할 수 있다. 이 떄, @apply@layer를 사용하여 커스텀 클래스를 만들어 적용할 수 있다.

<!-- Before extracting a custom class -->
<button class="py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75">
  Save changes
</button>

<!-- After extracting a custom class -->
<button class="btn-primary">
  Save changes
</button>
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .btn-primary {
    @apply py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75;
  }
}

** @apply, @layer에 대한 자세한 내용은 공식문서 참조 (Link)



6. 커스텀 스타일 지정

Bootstrap에 비해 Tailwind가 좋은 이유 중 하나가 바로 자유로운 커스텀이 가능한 것!

1) 테마 커스텀 지정

색상 팔레트, spacing, typography, breakpoint 등을 변경하려면 tailwind.config.js 파일에서 원하는 스타일을 추가하여 사용하면 된다.

module.exports = {
  theme: {
    screens: {
      sm: '480px',
      md: '768px',
      lg: '976px',
      xl: '1440px',
    },
    colors: {
      'blue': '#1fb6ff',
      'pink': '#ff49db',
      'orange': '#ff7849',
      'green': '#13ce66',
      'gray-dark': '#273444',
      'gray': '#8492a6',
      'gray-light': '#d3dce6',
    },
    fontFamily: {
      sans: ['Graphik', 'sans-serif'],
      serif: ['Merriweather', 'serif'],
    },
    extend: {
      spacing: {
        '128': '32rem',
        '144': '36rem',
      },
      borderRadius: {
        '4xl': '2rem',
      }
    }
  }
}

** 테마 커스터마이징에 대한 자세한 설명은 공식문서 참조 (Link)

2) 클래스명에 임의의 값을 적용

직접 특정한 값을 사용하여 스타일링 해야할 때 Tailwind는 대괄호 표기법을 사용하여 임의의 값을 가진 클래스를 인라인으로 즉시 생성할 수 있다.

<div class="top-[117px]">
  <!-- ... -->
</div>

hover:, lg:와 같은 수식자와 함께 사용하는 것도 가능하다.

<div class="top-[117px] lg:top-[344px]">
  <!-- ... -->
</div>

색상, 폰트 사이즈, pseudo-element 등 모든 요소에 사용할 수 있다.

<div class="bg-[#bada55] text-[22px] before:content-['Festivus']">
  <!-- ... -->
</div>

임의의 속성

Tailwind가 제공하는 유틸리티 클래스에 포함되지 않은 CSS 속성을 사용해야 할 경우 대괄호표기법을 사용하여 완전히 임의의 CSS를 사용할 수 있음

<div class="[mask-type:luminance] hover:[mask-type:alpha]">
  <!-- ... -->
</div>


7. 함수와 directives

1) directives

@tailwind

/**
 * This injects Tailwind's base styles and any base styles registered by
 * plugins.
 */
@tailwind base;

/**
 * This injects Tailwind's component classes and any component classes
 * registered by plugins.
 */
@tailwind components;

/**
 * This injects Tailwind's utility classes and any utility classes registered
 * by plugins.
 */
@tailwind utilities;

/**
 * Use this directive to control where Tailwind injects the hover, focus,
 * responsive, dark mode, and other variants of each class.
 *
 * If omitted, Tailwind will append these classes to the very end of
 * your stylesheet by default.
 */
@tailwind variants;

@layer

커스텀 스타일을 지정할 수 있다. 가능한 layer는 base, components, utilities.

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  h1 {
    @apply text-2xl;
  }
  h2 {
    @apply text-xl;
  }
}

@layer components {
  .btn-blue {
    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
  }
}

@layer utilities {
  .filter-none {
    filter: none;
  }
  .filter-grayscale {
    filter: grayscale(100%);
  }
}

@apply

기존의 유틸리티 클래스를 커스텀 CSS안에서 적용할 때 사용한다.

.select2-dropdown {
  @apply rounded-b-lg shadow-md;
}
.select2-search {
  @apply border border-gray-300 rounded;
}
.select2-results__group {
  @apply text-lg font-bold text-gray-900;
}

2) Functions

Tailwind 고유의 값에 액세스하기 위한 함수. Tailwind의 함수는 빌드 시 평가되어 최종 CSS에 정적값으로 반영된다.

theme()

Tailwind Config 값에 액세스하기 위한 함수

.content-area {
  height: calc(100vh - theme(spacing.12));
}

중첩된 값에 접근할 때 점 표기 사용

.btn-blue {
  background-color: theme(colors.blue.500);
}

screen()

미디어 쿼리로 반응형 스타일을 지정할 때 Tailwind에서 지정된 중단점 유틸리티 클래스를 참조한다.

@media screen(sm) {
  /* ... */
}

빌드 시 해당 유틸리티 클래스와 일치하는 미디어 쿼리가 생성된다.

@media (min-width: 640px) {
  /* ... */
}
profile
better than more

0개의 댓글