Skip to content

Tailwind CSS

Tailwind APIs (list)

  • Default
  • Customization
  • Base Styles
  • Layout
    • AspectRatio
    • Container
    • Columns
    • BreakAfter
    • BreakBefore
    • BreakInside
    • BoxDecorationBreak
    • BoxSizing
    • Display
    • Floats
    • Clear
    • Isolation
    • ObjectFit
    • ObjectPosition
    • Overflow
    • OverscrollBehavior
    • Position
    • Top/Right/Bottom/Left
    • Visibility
    • Z-Index
  • Flexbox & Grid
    • FlexBasis
    • FlexDirection
    • FlexWrap
    • Flex
    • FlexGrow
    • FlexShrink
    • Order
    • GridTemplateColumns
    • GridColumnStart/End
    • GridTemplateRows
    • GridRowStart/End
    • GridAutoFlow
    • GridAutoColumns
    • GridAutoRows
    • Gap
    • JustifyContent
    • JustifyItems
    • JustifySelf
    • AlignContent
    • AlignItems
    • AlignSelf
    • PlaceContent
    • PlaceItems
    • PlaceSelf
  • Spacing
    • Padding
    • Margin
    • SpaceBetween
  • Sizing
    • Width
    • Min-Width
    • Max-Width
    • Height
    • Min-Height
    • Max-Height
  • Typography
    • FontFamily
    • FontSize
    • FontSmoothing
    • FontStyle
    • FontWeight
    • FontVariantNumeric
    • LetterSpacing
    • LineHeight
    • ListStyleType
    • ListStylePosition
    • TextAlign
    • TextColor
    • TextDecoration
    • TextDecorationColor
    • TextDecorationStyle
    • TextDecorationThickness
    • TextUnderlineOffset
    • TextTransform
    • TextOverflow
    • TextIndent
    • VerticalAlign
    • Whitespace
    • WordBreak
    • Content
  • Backgrounds
    • BackgroundAttachment
    • BackgroundClip
    • BackgroundColor
    • BackgroundOrigin
    • BackgroundPosition
    • BackgroundRepeat
    • BackgroundSize
    • BackgroundImage
    • GradientColorStops
  • Borders
    • BorderRadius
    • BorderWidth
    • BorderColor
    • BorderStyle
    • DivideWidth
    • DivideColor
    • DivideStyle
    • OutlineWidth
    • OutlineColor
    • OutlineStyle
    • OutlineOffset
    • RingWidth
    • RingColor
    • RingOffsetWidth
    • RingOffsetColor
  • Effects
    • BoxShadow
    • BoxShadowColor
    • Opacity
    • MixBlendMode
    • BackgroundBlendMode
  • Filters
    • Blur
    • Brightness
    • Contrast
    • DropShadow
    • Grayscale
    • HueRotate
    • Invert
    • Saturate
    • Sepia
    • BackdropBlur
    • BackdropBrightness
    • BackdropContrast
    • BackdropGrayscale
    • BackdropHueRotate
    • BackdropInvert
    • BackdropOpacity
    • BackdropSaturate
    • BackdropSepia
  • Tables
    • BorderCollapse
    • BorderSpacing
    • TableLayout
  • Transitions & Animation
    • TransitionProperty
    • TransitionDuration
    • TransitionTimingFunction
    • TransitionDelay
    • Animation
  • Transforms
    • Scale
    • Rotate
    • Translate
    • Skew
    • TransformOrigin
  • Interactivity
    • AccentColor
    • Appearance
    • Cursor
    • CaretColor
    • PointerEvents
    • Resize
    • ScrollBehavior
    • ScrollMargin
    • ScrollPadding
    • ScrollSnapAlign
    • ScrollSnapStop
    • ScrollSnapType
    • TouchAction
    • UserSelect
    • WillChange
  • SVG
    • Fill
    • Stroke
    • StrokeWidth
  • Accessibility
  • Official Plugins
    • Typography
    • Forms
    • AspectRatio
    • LineClamp
    • ContainerQueries

Rapidly build modern websites without ever leaving your HTML.

Categories

UI Frameworks

Plugins

UI Frameworks (Copy & Paste)

Not tailwind

Dependencies

How to install

create-react-app + PostCSS

Installing Tailwind CSS as a PostCSS plugin

필수 패키지 설치:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

postcss.config.js 파일 설정:

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

tailwind.config.js 파일 설정:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

index.css파일 상단에 추가:

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

Getting set up

기본 셋업에 필요한 라이브러리:

CSS 적용 방법 (@apply 사용 방법)

@apply 사용하면 된다.

다음은 assets/scss/styles.scss에서 새로이 만든 .nav__link다. @apply를 이용해서 기존에 있던 utility classes를 나의 custom class에 적용할 수 있다.

@tailwind base;
@tailwind components;

.nav_link {
  @apply font-semibold text-gray-700 hover:border-gray-600 border-b-2 border-transparent;
  a {
    @apply block py-7 px-4;
  }
}

@tailwind utilities;

사용할 때 여러 줄에 걸쳐 사용한다면 media-query 적용이 안될 수 있다.

.today-text {
  @apply 2xl:tw-pl-2.5;
  @apply xl:tw-pl-2;
  @apply lg:tw-pl-1.5;
  @apply tw-pl-1;
}

는 안된다. 아래와 같이 바꿔라.

.today-text {
  @apply tw-pl-1 lg:tw-pl-1.5 xl:tw-pl-2 2xl:tw-pl-2.5;
}

Breakpoint 추가 방법

module.exports = {
  theme: {
    extend: {
      screens: {
        'xs': '480px',   // 새로운 브레이크포인트 추가
        '3xl': '1800px', // 초대형 화면 추가
      }
    }
  }
}

Divide 같은 > * + * 가 포함된 하위 Selector 가 존재하는 클래스가 적용되지 않을 경우

Divide Width 를 다음과 같이 커스텀 컴포넌트를 사용할 때:

<div className="divide-x-2">
  <Scrollbars>  <!-- 이게 커스텀 컴포넌트 -->
    <div>Item 1<div>
    <div>Item 2<div>
    <div>Item 3<div>
    <div>Item 4<div>
  </Scrollbars>
</div>

작동하지 않을 수 있다. <Scrollbars> 같은 커스텀 컴포넌트가 > * + * 쿼리에 해당하는 내용을 모두 잡아먹어서 작동하지 않는것 이다.

scss를 사용할 경우 다음과 같이 정의하면 된다.

$--divide-y-reverse: 0;
$--divide-opacity: 1.0;

.dailyWorkItem {
  @apply tw-p-2;
  @apply tw-cursor-pointer;
  @apply tw-space-y-2;

  &:not([hidden]) + &:not([hidden]) {
    border-style: solid;
    border-top-width: calc(1px * calc(1 - $--divide-y-reverse));
    border-bottom-width: calc(1px * $--divide-y-reverse);
    border-color: rgb(221 221 221 / $--divide-opacity);
  }

  &[data-selected=true] {
    @apply tw-bg-[#{$selected-color}];
  }

  &:hover {
    @apply tw-bg-[#{$hover-color}];
  }
}

WARNING

주의할 점은 CSS Modules를 사용할 경우 중첩된 클래스로 정의하면 작동하지 않는다.

Important modifier

SCSS에서 !important 적용 방법

@apply text-4xl #{!important};

또는 시작 부분에 ! 문자를 추가하여 유틸리티를 important할 수 있습니다.

<p class="font-bold !font-medium">
  This will be medium even though bold comes later in the CSS.
</p>

!는 항상 유틸리티 이름 앞, 변형 뒤에 붙지만 접두사 앞에 붙습니다.

<div class="sm:hover:!tw-font-bold">

음수 값 적용 방법

접두사(prefix)가 있을 경우, 음수 값에 대한 대시 한정자는 접두사 앞에 추가해야 하므로 tw-를 접두사로 구성한 경우 -mt-8-tw-mt-8이 됩니다.

<div class="-tw-mt-8">
  <!-- -->
</div>

변형을 위한 임의 값 (Arbitrary values but for variants)

예제1:

<div class="[&:nth-child(3)]:py-0">
  <!-- ... -->
</div>

예제2:

<div class="bg-white [@supports(backdrop-filter:blur(0))]:bg-white/50 [@supports(backdrop-filter:blur(0))]:backdrop-blur">
  <!-- ... -->
</div>

예제3:

<ul role="list" class="[&>*]:p-4 [&>*]:bg-white [&>*]:rounded-lg [&>*]:shadow space-y-4">
  <li class="flex">
    <img class="h-10 w-10 rounded-full" src="..." alt="" />
    <div class="ml-3 overflow-hidden">
      <p class="text-sm font-medium text-slate-900">Kristen Ramos</p>
      <p class="text-sm text-slate-500 truncate">[email protected]</p>
    </div>
  </li>
  <!-- ... -->
</ul>

예제4:

<ul role="list" class="hover:[&>li:nth-child(2)>div>p:first-child]:text-indigo-500 [&>*]:p-4 [&>*]:bg-white [&>*]:rounded-lg [&>*]:shadow space-y-4">
  <!-- ... -->
  <li class="flex">
    <img class="h-10 w-10 rounded-full" src="..." alt="" />
    <div class="ml-3 overflow-hidden">
      <p class="text-sm font-medium text-slate-900">Floyd Miles</p>
      <p class="text-sm text-slate-500 truncate">[email protected]</p>
    </div>
  </li>
  <!-- ... -->
</ul>

SCSS에서 반응형 적용 방법

.root {
  @apply container mx-auto;

  ...

  @screen lg {
    @apply flex items-center h-yourMain;
  }
}

JS에서 스타일 설정 받아오는 방법

import resolveConfig from 'tailwindcss/resolveConfig'
import tailwindConfig from './tailwind.config.js'

const fullConfig = resolveConfig(tailwindConfig)

fullConfig.theme.width[4]
// => '1rem'

fullConfig.theme.screens.md
// => '768px'

fullConfig.theme.boxShadow['2xl']
// => '0 25px 50px -12px rgba(0, 0, 0, 0.25)'

TypeScript 사용시 src/ 디렉토리 제한이 걸린다면

tailwind.config.js 파일을 다음과 같이 사용하면 된다:

const tailwindConfig = require("./src/tailwind.config");

module.exports = tailwindConfig;

DarkMode 를 class 주입 방식 (구식) 으로 변환

tailwind.config.js파일에 darkMode를 'class' 값으로 변경.

module.exports = {
  darkMode: 'class',
};

버튼 이벤트 또는 state 변경 위치에:

  const [darkMode, setDarkMode] = useRecoilState(darkModeState);

  useEffect(() => {
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode]);

피치못할 사정으로 직접 구현된 상위 elem 의 class 명 찾을 때 방법

이미 구현된 Elem 구조상 wrap--darkMode 클래스가 "html ~ [여기 어딘가] ~ info-card" 에 위치할 때 일 때, 적용 방법:

@mixin info-card {
  @apply tw-bg-white;
  @apply tw-border;
  @apply tw-border-solid tw-border-[#ddd];
  @apply tw-rounded-md;
  @apply tw-shadow-md;
  @apply tw-p-2.5;

  :global(html .wrap--darkMode) & {
    @apply tw-bg-[#222538];
    @apply tw-border-0;
  }
}

CSS Module을 사용한다면 :global을 적용해야한다.

Troubleshooting

Tailwind + SCSS: resolve-url-loader: error processing CSS, invalid mapping

빌드할 경우 다음과 같은 에러가 출력될 수 있다.

Creating an optimized production build...
Failed to compile.

Error: resolve-url-loader: error processing CSS
  Invalid mapping: {"generated":{"line":1,"column":994},"source":"file:///home/your/Project/steelanalysissystem-inspection-webui/src/components/InfoCard.module.scss","original":{"column":null},"name":null}

줄 끝의 일회성 스타일 (e.g. max-w-[500px])를 앞 쪽으로 이동해야 한다. (맨 마지막에 있으면 안된다)

다음과 같은 코드는

@apply mt-5 max-w-[500px];

다음과 같이 변경한다.

@apply max-w-[500px] mt-5;

한 줄에 여러 지시문이 있으면 대괄호를 사용하는 항목이 마지막에 오지 않도록 계속해서 순서를 변경하거나 직접 css 로 다시 작성하면 된다.

Object.hasOwn is not a function TypeError: Object.hasOwn is not a function

Tailwind CSS:
  Tailwind CSS: Object.hasOwn is not a function TypeError:
    Object.hasOwn is not a function at /home/your/Project/your-web/node_modules/daisyui/src/theming/functions.js:75:18
    at Array.forEach ( )
    at Object.convertColorFormat (/home/your/Project/your-web/node_modules/daisyui/src/theming/functions.js:74:27)
    at /home/your/Project/your-web/node_modules/daisyui/src/theming/functions.js:184:39
    at Array.forEach ( )
    at Object.injectThemes (/home/your/Project/your-web/node_modules/daisyui/src/theming/functions.js:183:28)
    at mainFunction (/home/your/Project/your-web/node_modules/daisyui/src/index.js:59:40)
    at registerPlugins (/home/your/Project/your-web/node_modules/tailwindcss/lib/lib/setupContextUtils.js:796:61)
    at createContext (/home/your/Project/your-web/node_modules/tailwindcss/lib/lib/setupContextUtils.js:1198:5)
    at Object.module (/home/your/Applications/pycharm-professional-2022.1.3/plugins/tailwindcss/server/tailwindcss-language-server:2961:6934)

저 오류가 IntelliJ 계열에서 발생되었다면 node Interpreter 경로 설정을 확인해 보자:

Intellij-nodejs-settings.png

See also

  • CSS
  • webfont
  • Emotion CSS
  • PostCSS - PostCSS는 일상적인 CSS 동작을 자동화하기 위해 자바스크립트 기반 플러그인을 사용하는 소프트웨어 개발 도구이다.
  • PurgeCSS - 사용 안하는 CSS 찾아서 삭제해주는 도구

Favorite site