Home Tailwind Basics
Post
Cancel

Tailwind Basics

Text

A screenshot

Colour classes available here. Some examples:

1
class="text-slate-50"

Note that we can declare this on the entire body, and this will apply to everything. However, if we add a different class to an element inside the main body, then that will override the body settings.

Text size classes available here.

Examples:

1
2
3
4
5
<p class="text-sm ...">The quick brown fox ...</p>
<p class="text-base ...">The quick brown fox ...</p>
<p class="text-lg ...">The quick brown fox ...</p>
<p class="text-xl ...">The quick brown fox ...</p>
<p class="text-2xl ...">The quick brown fox ...</p>

We can also use things like ‘uppercase’ to make it all caps, or font-bold to make it bold.

Custom fonts

By default, tailwind has ‘sans’, ‘serif’ and ‘mono’ and different fonts within them ‘system-ui’, ‘apple-system’ etc. If we don’t specify and font classes, the sans font is used by default. We can change it like this though.

1
class="font-mono"

To add from google fonts, select what you want, choose the @import option and copy the output to styles.css

1
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap');

You can reference this in the tailwind config file.

1
2
3
4
5
extend: {
    fontFamily: {
        body: ['Roboto'] // same name as google fonts
    }
}

We then run the build script:

1
npm run build-css

And can use it like this:

1
class="font-roboto"

Margin Border Padding

You can see what each are below:

You can specify margin and padding to the l (left) r (right) t (top) b (bottom) x (left and right) or y (top and bottom).

1
2
3
4
5
6
mx-1
pt-2
border-b
border-t
border-y border-gray-200
etc.

Margin docs

Padding docs

Border docs

You can choose the size of the border and the colour of it too. This can be very useful if you are trying to create badges that look like this.

image-20220810235742422

1
2
3
4
<div class="px-4 py-5 bg-white shadow rounded-lg overflow-hidden sm:p-6 border-r-8 border-red-400">
    <dt class="text-sm font-medium text-gray-500 truncate">Total NFT Supply</dt>
    <dd class="mt-1 text-3xl font-semibold text-gray-900">4,891</dd>
</div>

Tailwind Config

We can override defaults in tailwind to extend rules, or give extra classes.

To create the config file:

1
npx tailwindcss init

Although we shouldn’t use the full version in practise, we can do when practising to see what we need to change:

1
npx tailwindcss init --full

Full allows us to see all the default classes. Tailwind must be named tailwing.config.js (as it will be by default). You can just add to the key value pairs, or change existing ones.

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
    theme: {
        extends: {
            primary: '#FF6363',
            secondary: {
       			100: 'FF6364',
                200: 'FF6365'
    		} 
        }       
	}
}

We then need to reprocess the styles.

1
npm run build-csss

We could then use it in the html as a class: ‘text-mammoth’.

Flex

A good way to define layout. Full docs here. The default behaviour of flex items is to sit next to each other. We can justify differently using classes.

1
2
3
4
<div class="flex justify-center">
    <a href="#">Login</a>
    <a href="#">Register</a>
</div>

We can use justify-start to have them follow each other in the middle of the flex box, center to stick them in the middle, or end to put them together on the right hand side. between adds space between elements but not on outside, around puts space around the elements too, and evenly puts even space around all the elements.

We may want to add some margin so there is a bit of a gap, otherwise they come straight after each other.

We can also use flex in the opposite direction (vertical y instead of x axis, within a row).

<div class="flex"> 
	<div class="bg-red-500 h-4 w-6"></div>
	<div class="bg-blue-500 h-8 w-6"></div>
	<div class="bg-green-500 h-12 w-6"></div>
</div>

image-20220810192411185

‘flex items-end’ aligns from bottom up (end of y axis):

image-20220810192547537

From the middle of the y axis using ‘flex items-center’:

image-20220810192640641

You can next flex boxes within another flex component. For example:

image-20220810201715018

1
2
3
4
5
6
7
8
9
10
<header class="flex items-center justify-between bg-black"><div class="text-white m-2">
        Icon
    </div><div class="flex"><div class="text-white m-2">
            Link1
        </div><div class="text-white m-2">
            Link2
        </div>
    </div>

</header>

Grid

This allows us to add content into grids with rows and columns. We use a grid container to surround the grid.

image-20220810232900588

1
2
3
4
5
6
7
8
9
10
11
<div class="grid md:grid-cols-3 lg:grid-cols-4 gap-2">
    <div class="h-10 bg-red-500"></div>
    <div class="h-10 bg-blue-500"></div>
    <div class="h-10 bg-green-500"></div>
    <div class="h-10 bg-yellow-500"></div>
    <div class="h-10 bg-red-500"></div>
    <div class="h-10 bg-red-500"></div>
    <div class="h-10 bg-blue-500"></div>
    <div class="h-10 bg-green-500"></div>
    <div class="h-10 bg-yellow-500"></div>
</div>

Responsive Design

We can use sm, md, lg, xl, and 2xl before tailwind classes so that those classes only apply to the specifed classes and up.

Breakpoint prefix Minimum width CSS
sm 640px @media (min-width: 640px) { ... }
md 768px @media (min-width: 768px) { ... }
lg 1024px @media (min-width: 1024px) { ... }
xl 1280px @media (min-width: 1280px) { ... }
2xl 1536px @media (min-width: 1536px) { ... }

In the example below, the default for tiny tiny screens is purple. Then when we get to a ‘small’ screen size, it changes to red, a medium size and up it changes to blue and then a large screen and up it changes to red.

1
2
<p class="text-purple-500 sm:text-red-500  md:text-blue-500 lg:text-green-500">Watch me change!</p>

Hiding elements

You may want to use this to hide elements. For example, a burger menu could be set to be invisible if the screen size is small or up:

1
<div class="sm:invisible"></div>

Invisible still maintains that element in the dom. Hidden removes it from the page layout.

1
<div class="sm:hidden"></div>

The opposite of hidden is block. So we can have something that is hidden on smaller screens but is displayed on larger screens like this:

1
<div class="sm:hidden"></div>

Using JS to show and hide something can work like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>    
	<p id='unlockSecretText'>Click me</p>
    <p class="hidden" id="secretText">Shh! Don't tell anyone!</p>
</html>

<script>
    const unlockSecretText = document.querySelector('#unlockSecretText')
    const secretText = document.querySelector('#secretText')

    unlockSecretText.addEventListener('click', () => {
        if (secretText.classList.contains('hidden')) {
            secretText.classList.remove('hidden');
        } else {
            secretText.classList.add('hidden');
        }
    })
</script>

Alpine makes this even shorter. We set a variable called toggled which starts as false. When the first element is clicked, we set toggled to be the opposite of the boolean value it is set at (i.e. true to false, false to true). The second element has a conditional class which uses the ternary operator to set the hidden class only if toggled is false. If it is true then the class is ‘’ (i.e. nothing).

1
2
3
4
<div x-data="{ toggled: false }">
    <p x-on:click="toggled = ! toggled">Toggle me!</p>
    <p :class="toggled ? '' : 'hidden'">I appear when toggled!</p>
</div>

Or even shorter for the second version, which basically reads: if toggled is true, then set the class to ‘hidden’.

1
<p :class="toggled | 'hidden'">I appear when toggled!</p>

Cards

We can give rounded corners using the corner class, and by specifying options.

1
2
class="corner"
class="corner-sm"

If we want to apply the rounded corners to a div which contains an image, we should set overflow to be hidden so that the images don’t go beyond the rounded corners.

1
class="rounded overflow-hidden"

We can set a shadow around the card:

1
class="rounded overflow-hidden shadow-md"

Width and Height

If we want the width of something to go the full width of the component it is in:

1
w-full

Images

If you have an image in a card and don’t want the image to be distorted as the screen size changes, and as it fills the component it is in, use the object-cover property.

1
object-cover

Positional layout

We can set the parent element to be relative, and then the child element to be absolute, if we want to define where the child is in relation to the parent. The example below could be useful if you are trying to put a badge in the top left corner of a component.

image-20220810224940710

1
2
3
<div class="bg-yellow-300 w-1/4 relative">
    <div class="bg-green-300 h-4 w-4 absolute top-0 ml-2 mt-2"></div>
</div>

Extracting classes to components

Tailwind can lead to long class names… and if you need to change something it’s a pain to change it everywhere. So, if you are reusing the code, it is best to create custom classes which contain the tailwind classes already. For example, we could have a card component.

In styles.css, define your custom class name:

1
2
3
4
5
6
7
8
9
...

.card {
    @apply rounded bg-white border-gray-200 shadow-md overflow-hidden relative;
}

.badge {
    @apply absolute top-0 ml-2 p-2 mt-2 text-xs uppercase font-bold rounded-full;
}

We then need to run the build command again: npm run build-css. If using vite in laravel, as long as you have npm run dev going, you’ll be fine without needing to do anything else!

And then we can use it in the html as follows, which makes things a lot cleaner!

1
2
3
4
5
6
7
8
9
10
<div class="card"> 
    <img src="img/stew.jpg" alt="stew" class="h-32 sm:h-48 w-full object-cover">
    <div class="m-4">
        <span class="font-bold">5 Bean Chili Stew</span>
        <span class="block text-gray-500 text-sm">Recipe by Mario</span>
    </div>
    <div class="badge">
        <span>25 mins</span>
    </div>
</div>

Button

Here is how we could do a button.

image-20220810233740113

Set the class in styles.css:

1
2
3
.btn{
  @apply rounded-full py-2 px-3 uppercase text-xs font-bold tracking-wider cursor-pointer;
}

And use as follows:

1
2
3
<div class="mt-12 flex justify-center">
    <div class="btn text-white">Load more</div>
</div>  

Icons

You can get icons from Hero Icons, which is made by the same people who made tailwind. Find the icon, copy as an svg, paste into the html, add a class to specify the width (and anything else you want to do).

Often when using icons, we want them to show up next to the text. We could use flex for this, but an easier way is just to specify that the class is ‘inline-block’. If you specifically want it to be displayed underneath, you could use ‘block’ although that is the default.

1
2
<svg class="w-5 inline-block" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>

Hover

We can apply a hover effect by using the hover class followed by the class we want to use when the element is hovered over.

1
<p class="hover:text-red-400">Hover over me</p> 

You may want to increase a shadow when you hover over a card.

1
hover:shadow-inner

Or change the colour and text colour of a button when hovered over.

1
hover:bg-black hover:text-white

Transition

When hovering, it can be nice to add a transition, which is a short animation between the start state, and the end state. In the example below a blue rectangle changes to red when hovered over. We use the ease-out transition style and specify that the transition should take 500ms to change.

1
2
<div class="h-24 bg-blue-500 hover:bg-red-300 transition ease-out duration-500"></div>

We can use the following easing functions: ease-linear (smooth), ease-in (slower to begin but speeds up), ease-out (fast at beginning and slows down), or ease-in-out (fast at end and start, but slow in middle.)

Tailwind Libraries

Daisy UI - Tailwind component library. Nice designs, easily customisable, includes JS for components and lots of built in themes. Looks like a very easy way to get up and running quickly.

Tailwind Elements - Components + interactivity. Recreates bootstrap components.

Tailblocks - Copy and paste tailwind components.

Tailwind UI - Paid for component library by the makers of tailwind.

Meraki UI - Copy and paste tailwind components.

Flowbite - Interactive tailwind components with JS built in.

Hyper UI - Tailwind component library.

This post is licensed under CC BY 4.0 by the author.