Tailwind

hwisaac·2023년 1월 27일
0

Tour of Tailwind

  • tawilwindutility-first css 이다. (즉 테일윈드가 많은 클레스네임을 갖는 다는 말. 엄청 큰 css 파일이다.)
  • 스타일을 할때 클래스 네임을 조합해서 하면 된다.
  • vscodeextension : Tailwind CSS intelliSense 를 설치하면 자동완성 기능을 쓸 수 있다.
  • 자동완성이 안뜨면 컨트롤+스페이스 cmd + space 를 눌러본다

자주쓰는 것

  • flex
  • p 패딩
  • m 마진
  • bg 백그라운드
  • space 자식요소에 마진을 준다 ex) space-y-5 (자식요소에 mt-5 와 mb-5 줄수 있다.) -> tailwind 가 계산해준다 [ helper class ]
  • rounded
  • gap
  • shadow 그림자
  • font 글자 굵기
  • text 글자크기, 색상, 정렬
  • justify 플렉스정렬
  • items 플렉스 정렬
  • border 테두리
  • w 너비 ex) w-2/4 는 width: 50%;
  • h 높이
  • overflow 오버플로우
  • relative : relative 포지션
  • -top 음수넣고 싶을 때 ex) -top-14 는 -14 만큼 올라감
  • min 최소값 정할 때 ex) min-height-screen
  • max
  • aspect ex) aspect-square

Modifier [문서]

  • 일반 css 에서 마우스 호버시 효과를 주려면 :hover 선택자를 사용했다.
  • tailwind 에서는 modifier 를 사용할 수 있다.
  • 조건:프로퍼티 ex) hover:text-black
<button
  className="mt-5 bg-blue-500 text-white p-3
  text-center rounded-xl w-3/4 mx-auto 
  hover:bg-teal-500 hover:text-black
  active:bg-yellow-500 focus:bg-red-500
  ">
  Checkout
</button>

transition

  • focus modifier
  • ring utility: ex) ring-2 , ring-offset-2, ring-yellow-500
    • 모두 앞에 focus 를 해줄 필요는 없다. 다른 애들은 변수에 대한 설정이므로 focus:ring-2 만 해도 충분
<div className="space-x-2">
  <button
    className="w-5 h-5 rounded-full bg-yellow-500 focus:ring-2 ring-offset-2 ring-yellow-500 transition" />
  <button
    className="w-5 h-5 rounded-full bg-indigo-500 focus:ring-2 ring-offset-2 ring-indigo-500 transition" />
  <button
    className="w-5 h-5 rounded-full bg-teal-500 focus:ring-2 ring-offset-2 ring-teal-500 transition" />
</div>

modifier for lists

<ul>
  {[1, 2, 3, 4].map((i) => (
  <div
    key="{i}"
    className="flex justify-between my-2 odd:bg-blue-50 even:bg-yellow-50 first:bg-teal-50 last:bg-amber-50">
    <span className="text-gray-500">Grey Chair</span>
    <span className="font-semibold">$19</span>
  </div>
  ))}
</ul>
<ul>
  {["a", "b", "c", ""].map((c, i) => (
  <li className="bg-red-500 py-2 empty:bg-blue-500" key="{i}">{c}</li>
  ))}
</ul>
  • empty 에 대해서도 디자인 입힐 수 있다. ex) empty:hidden
  • hidden 을 해버리면 display : none 과 같다

Modifier for group

  • 기본 css에서는 특정 컨테이너에 마우스를 올릴때 그 안의 아이템의 스타일을 변경하고 싶다면 아래처럼 했다.
.container:hover .item {
}
  • tailwind 에서는 이렇게 하면 된다.
    1. 컨테이너에 group 이라는 클래스명을 준다
    2. 아이템에게 group 에 마우스를 hover 하면 변화할 것을 정해준다 group-hover:bg-red-300
<div className="group">
  <div className="group-hover:bg-red-300">
</div>

modifier for forms

  • placeholder-shown

  • disabled

  • required

  • invalid

  • valid

    peer modifier

    • input의 상태에 따라 span 의 스타일을 변경할 수 있다.
      1. input 을 정하고 peer 클래스명을 추가한다.
      2. peer 의 sibling 레이블에 peer-modifier 로 스타일을 입힌다.
<form className="flex flex-col space-y-2  p-5 ">
  <input
    type="text"
    required
    placeholder="Username"
    className="border p-1 peer border-gray-400 rounded-md " />
  <span className="hidden peer-invalid:block peer-invalid:text-red-500">
    This input is invalid
  </span>
  <span className="hidden peer-valid:block peer-valid:text-teal-500">
    Awesome username
  </span>
  <span className="hidden peer-hover:block peer-hover:text-amber-500">
    Hello
  </span>
  <input type="submit" value="Login" className="bg-white" />
</form>

more modifiers

많은 사람들이 사용했던 패턴

  • selection 텍스트를 드래그 할때 스타일
  • open details 가 열렸을 떄
  • marker ul 리스트의 왼쪽에 있는 bullet의 스타일
<details className='selection-none open:bg-indigo-400'>
  <summary className='selection-none cursor-pointer'>details 의 제목</summary>
  <span className='selection:bg-indigo-600'>내용</span>
</details>

<ul className='list-disc marker:text-teal-500'>
  <li>item</li>
  <li>item</li>
  <li>item</li>
</ul>

파일 인풋 디자인하기

<input type="file" className="file:border-0 file:rounded-md file:bg-purple-400" >

modifier 중첩시키기

<div className='flex flex-col space-y-2  p-5 '>
  <p className='first-letter:text-7xl first-letter:hover:text-purple-400'>
    Hello everyone!
  </p>
</div>

응답형 modifier

  • tailwind 는 모바일 화면을 위한 스타일이 디폴트다.
  • 더 사이즈 큰 경우에 대해 따로 스타일을 설정해 줘야 한다.
  • sm , md, lg, xl, 2xl, portrait, landscape
  • 적용시 오른쪽으로 갈수록 큰 사이즈에 대해 스타일을 적용한다.
  • portrait, landscape 는 모바일 방향에 따른 것이다 (device simulator 에서 테스트 해볼 수 있다.)
<div className='bg-white sm:hover:bg-pink-800 sm:bg-red-400 md:bg-teal-400 lg:bg-indigo-400 xl:bg-yellow-400 2xl:bg-pink-500  p-6 rounded-3xl shadow-xl'></div>

Dark mode

  • 다크모드를 어떻게 활성화시킬지에 따라 고를수 있는 옵션들이 있다
  • 디폴트로 다크모드는 컴퓨터 환경에 따라 설정된다. (pc나 모바일을 다크모드로 설정했으면 브라우저도 따라간다.)
  1. 브라우저 설정을 따르지 않게 하려면 tailwind.config.jsdarkmode 옵션을 class 로 변경한다. (deefaultdarkMode: "media" )
    • 이렇게 되면, dark 클래스를 갖는 부모요소의 모든 자식요소도 다크모드가 적용된다.
    • class 모드에서 다크모드를 토글하고 싶으면, dark: 선택자를 사용하는 요소의 부모요소에 dark 클래스를 추가하면 된다. ex) 보통은 body 나 html 태그에 추가한다
  2. dark 를 클래스명에 넣는다
// tailwind.config.js
module.exports = {
  content: [
    "./pages/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  darkMode: "class",
  plugins: [],
};
      <div className="bg-white dark:bg-black flex flex-col justify-between p-6 rounded-3xl shadow-xl">
        <span className="font-semibold dark:text-white text-2xl">
          Select Item
        </span>
        <ul>
          <div className="flex justify-between my-2 ">
            <span className="text-gray-500 dark:text-gray-100">Grey Chair</span>
            <span className="font-semibold dark:text-white">$19</span>
          </div>
          <div className="flex justify-between my-2 ">
            <span className="text-gray-500 dark:text-gray-100">Grey Chair</span>
            <span className="font-semibold dark:text-white">$19</span>

tailwind 는 큰파일? (JIT)

  • 에전에 배포를 위해 빌드를 하면 필요 없는 css 들을 없애서 용량을 줄이는 과정을 거쳤다. 일명 purging 프로세스
  • 지금은 코드를 감시하면서 실시간으로 css를 업데이트 한다

tailwind 가 제공하지 않는 옵션을 사용하고 싶은 경우

text-9xl 보다 크게 하려면?

  • text-[500px] 를 하면 된다! JIT 덕분

  • 백그라운드 이미지 넣을 때 : bg-[url('https://~')]

Tailiwnd practice

tailwind 함수 만들기

function cls(...classnames: string[]) {
  return classnames.join(" ");
}

<button
  className={cls(
    "pb-4 font-medium border-b-2 ",
    method == "email"
      ? "border-orange-500 text-orange-400"
      : "border-transparent"
  )}></button>;

tailwind plugin : tainwindcss/form

  1. form 의 기본 스타일을 갖게 해주는 플러그인을 추가해보자
  2. npm i @tailwindcss/forms : input 에 reset layer 를 추가할수 있는 플러그인을 설치한다
  3. tailwind.config.js 에서 plugins 배열에 추가해준다. : plugins: [require("@tailwindcss/forms")]
module.exports = {
  content: [
    "./pages/**/*.{js,jsx,ts,tsx}",
    "./components/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  darkMode: "media", // class
  plugins: [require("@tailwindcss/forms")],
};

form 태그 사용해보기

  1. appearance-none 으로 혹시 input 이 갖고 있을지 모르는 기본 스타일을 리셋 시켜보자
<form className='flex flex-col mt-8'>
  <label className='text-sm font-medium text-gray-700'>
    {method === "email" ? "Email address" : null}
    {method === "phone" ? "Phone number" : null}
  </label>
  <div className='mt-1'>
    {method === "email" ? (
      <input
        type='email'
        className='appearance-none w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-orange-500 focus:border-orange-500'
        required
      />
    ) : null}
    {method === "phone" ? (
      <div className='flex rounded-md shadow-sm'>
        <span className='flex items-center justify-center px-3 rounded-l-md border border-r-0 border-gray-300 bg-gray-50 text-gray-500 select-none text-sm'>
          +82
        </span>
        <input
          type='number'
          className='appearance-none w-full px-3 py-2 border border-gray-300 rounded-md rounded-l-none shadow-sm placeholder-gray-400 focus:outline-none focus:ring-orange-500 focus:border-orange-500'
          required
        />
      </div>
    ) : null}
  </div>
  <button className='mt-5 bg-orange-500 hover:bg-orange-600 text-white py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium focus:ring-2 focus:ring-offset-2 focus:ring-orange-500 focus:outline-none '>
    {method === "email" ? "Get login link" : null}
    {method === "phone" ? "Get one-time password" : null}
  </button>
</form>

tip: divde 클래스

  • 컴포넌트 리스트에서 border-bottom 속성으로 밑줄을 그었을 때 마지막 컴포넌트의 밑줄이 안그려지게 하고싶다.
  • 방법1: last:border-b-0 클래스 명을 추가해주면 된다.
<div className='py-10'>
  {[1, 1, 1, 1, 1, 1, 1].map((_, i) => (
    <div
      key={i}
      className='flex px-4 cursor-pointer py-3 items-center space-x-3 border-b last:border-b-0'>
      <div className='w-12 h-12 rounded-full bg-slate-300' />
      <div>
        <p className='text-gray-700'>Steve Jebs</p>
        <p className='text-sm  text-gray-500'>
          See you tomorrow in the corner at 2pm!
        </p>
      </div>
    </div>
  ))}
</div>
  • 방법2: 부모 요소에서 divide 클래스를 사용한다. (divide-y-[1px] 세로방향으로 나눠서 쌓는다. 경계는 1px)
  • divide 는 요소 옆에 형제 요소가 있으면 사이에 border를 넣어준다.
<div className='py-10 divide-y-[1px] '>
  {[1, 1, 1, 1, 1, 1, 1].map((_, i) => (
    <div
      key={i}
      className='flex px-4 cursor-pointer py-3 items-center space-x-3'>
      <div className='w-12 h-12 rounded-full bg-slate-300' />
      <div>
        <p className='text-gray-700'>Steve Jebs</p>
        <p className='text-sm  text-gray-500'>
          See you tomorrow in the corner at 2pm!
        </p>
      </div>
    </div>
  ))}
</div>

tip: aspect

  • aspect-video: 영상비율(16:9) 로 만들어준다. (가로를 반응형으로 바꾸면 세로도 알아서 조절됨)
  • aspect-square : 정사각형 비율로 만들어준다.

0개의 댓글