Skip to content

Tailwind Getting Started Guide

Botho edited this page Nov 23, 2023 · 7 revisions

Official Docs

Working with tailwind in the frontend

Setup

First make sure to setup VSCode correctly.

For the best tailwind experience you should have at least Prettier and Tailwind CSS IntelliSense installed and add this setting to your config:

"tailwindCSS.experimental.classRegex": ["cn\\(([^)]*)\\)"]

Getting started

Usually just using a string is enough.

<div className="bg-brand-100 p-3">
  ๐Ÿ‘‹
</div>

For everything more complex we have the cn helper. It's basically a wrapper around clsx.

You can use it for conditional classes and multiple lines to make complex styles more readable.

Example with a lot of classNames

<button
  className={cn(
    `mt-10 block inline-block w-full border border-transparent px-[22px] py-2 py-2
    text-lg font-bold shadow-menu transition-all hover:border-black focus-visible:border-black`
  )}
>
  ๐Ÿ‘ 
</button>

The indentation has to be done manually unfortunately, but Prettier sorts the classNames automatically even across the lines.

Example with conditionals

<div
  className={cn(
    'text-base italic',
    inlineFeedback ? 'ml-3 inline-block' : 'mt-5'
  )}
>
  ๐Ÿ‘‹ 
</div>

Like in clsx you can pass multiple arguments to cn. Even different types are supported so you can mix and match template strings, strings and conditionals.

Move from styled or styled components to tailwind

before:

<StyledDiv></StyledDiv>

const StyledDiv = styled.div`
  display: flex;
`

after:

<div className="flex"></div>

Spacing

styled.div`
  margin: 24px 12px 6px;
`

=> mx-3 mt-6 mb-1.5

Colors

styled.div`
  color: ${(props) => props.theme.colors.brand};
`

=> text-brand

Responsive

styled.div`
  @media (min-width: ${(props) => props.theme.breakpoints.sm}) {
    margin-bottom: 20px;
  }
`

=> sm:mb-5

Hover

styled.div`
  &:hover {
    text-decoration: underline;
  }
`

=> hover:underline

Many classes

before:

<div className="mx-2 mt-4 mb-0.5 text-lg text-brand bg-white hover:bg-brand"></div>

after:

<div
  className={clsx(
    'mx-2 mt-4 mb-0.5 text-lg text-brand',
    'bg-white hover:bg-brand'
  )}
></div>

(not more than 5 classes per line)

Helper

makeMargin => mx-side

makePrimaryButton => serlo-button serlo-make-interactive-primary

Props

before:

<LinkSection full={isFull}/>

const LinkSection = styled.div<{ full?: boolean }>`
  margin-bottom: ${(props) => props.full && '1.5rem'};
  margin-top: ${(props) => (!props.full ? '20px' : '8px')};
`

after:

<LinkSection className={clsx(isFull ? 'mb-6 mt-2' : 'mt-5')}
Clone this wiki locally