knowledge-kitchen
/
course-notes
class: center, middle # The Tailwind CSS Front-End Framework modern, utility-first styling for the web --- # Agenda 1. [Front-End Frameworks](#frameworks) 1. [Tailwind Overview](#overview) 1. [Installation](#installation) 1. [Utility-First Styling](#utility-first) 1. [Separation of Concerns?](#separation) 1. [Responsive Design](#responsive-design) 1. [Flex & Grid Layout](#layout) 1. [Customization](#customization) 1. [Interactive Components with Alpine.js](#alpine) 1. [Conclusions](#conclusions) --- name: frameworks # Front-End Frameworks -- ## Concept Front-end frameworks, of which Tailwind CSS is one, are toolkits that _help web developers create the front-end_ - the visible user interfaces of web pages and applications. -- - They do so by offering _readymade styles_ (written in [CSS](../css)) that the web developer can apply to their own [HTML](../html) elements just by adding class names. -- - They are generally created in such a way that the _web designer need not know how they work_, but simply must know how to apply them properly. -- - The most successful front-end frameworks are those that offer the most commonly-used styles in the easiest-to-use way. --- template: frameworks ## Two flavors Front-end frameworks generally fall into one of two categories. -- - **Component frameworks** - like the older [Bootstrap](../bootstrap) framework - give you large, pre-designed components (buttons, navigation bars, cards, etc.) that all look a certain way out of the box. -- - **Utility frameworks** - like Tailwind CSS - give you many tiny single-purpose classes (one for color, one for padding, one for font size, etc.) that you combine together to build any design you want. -- - Utility frameworks have become the more popular choice in recent years because they offer more design flexibility without writing custom CSS. --- name: overview # Tailwind Overview -- ## Evolution [Tailwind CSS](https://tailwindcss.com) was first released by Adam Wathan in 2017 as a reaction to the limitations of component-based frameworks like Bootstrap. -- - It is maintained by **Tailwind Labs** and a large community of open-source contributors. -- - It is now **one of the most widely used CSS frameworks**, popular with both beginners and professional developers. -- - Tailwind CSS is given away free under the **MIT** open-source license. --- template: overview ## Concept Tailwind CSS is a free collection of small, single-purpose CSS classes for building websites and web applications. It contains ... -- - **a built-in CSS reset** (called [Preflight](https://tailwindcss.com/docs/preflight)) that removes the browsers' inconsistent default styles so that every project starts from the same clean baseline. -- - **hundreds of utility classes** for things like color, spacing, typography, borders, shadows, and more - each class does exactly one small thing. -- - **responsive design built in** - every utility class can be applied only at certain screen sizes by adding a prefix like `md:` or `lg:`. -- - **layout utilities** for flexbox and CSS grid, making it easy to position elements without writing any custom CSS. -- - **state utilities** so you can change styles when the user hovers, focuses, or clicks on an element, with prefixes like `hover:` and `focus:`. --- name: installation # Installation -- ## The easy way: the Play CDN Unlike many modern tools, Tailwind CSS can be added to a web page with a **single line of code** - no terminal commands, no installations, no setup files. -- - Add the following `script` tag to the `head` element of your HTML document. ```html ``` -- - That's it. All of Tailwind's classes are now available to use anywhere in your HTML. -- - This approach is called the **[Play CDN](https://tailwindcss.com/docs/installation/play-cdn)**. A CDN (Content Delivery Network) is a cloud-based hosting environment that delivers files quickly from the nearest data center. -- - The Play CDN is officially supported by Tailwind for **learning, prototyping, and small personal projects**. Larger professional projects typically use a [more advanced setup](https://tailwindcss.com/docs/installation/using-vite), but you do not need to worry about that yet. --- template: installation ## A complete starter file Here is a complete, working HTML file that uses Tailwind CSS: ```html
My Tailwind Page
Hello, Tailwind!
``` -- - The `text-3xl` class makes the text large, `font-bold` makes it bold, and `text-blue-600` makes it blue. No CSS file required. --- template: installation ## Customization You can still write your own CSS code alongside Tailwind whenever you want. -- - _After_ the link to the Tailwind script in the code, add a link to your own custom CSS file. ```html
``` -- - Write any custom CSS rules in your `custom.css` file. They will work alongside Tailwind's utility classes. -- - However, with Tailwind you will find that _you rarely need to write custom CSS at all_ - the utility classes can handle most of what you want to do. --- name: utility-first # Utility-First Styling -- ## Concept Instead of writing CSS in a separate stylesheet, with Tailwind you _style elements directly_ by adding utility classes to them in your HTML. -- - Each class does **one small thing**. For example: - `p-4` adds padding of `1rem` on all sides. (See [CSS sizing units](../css#sizing-units) for what `rem` means.) - `bg-yellow-200` sets the background color to a light yellow. - `text-center` centers the text. - `rounded-lg` gives the element large rounded corners. -- - You combine these classes together to build any design you want. ```html
Click me!
``` -- - This creates a blue button with white text, comfortable padding, and rounded corners - all without writing a single line of custom CSS. --- template: utility-first ## Common utilities A small sampling of the most useful Tailwind utility classes: -- - **Color** - `text-red-500`, `bg-green-200`, `border-gray-400` -- - **Spacing** - `p-4` (padding), `m-2` (margin), `px-6` (padding left+right), `mt-8` (margin top) -- - **Typography** - `text-sm`, `text-xl`, `font-bold`, `italic`, `underline` -- - **Borders** - `border`, `border-2`, `border-blue-500`, `rounded`, `rounded-full` -- - **Sizing** - `w-full` (full width), `w-1/2` (half width), `h-screen` (full screen height, equivalent to `100vh` - see [CSS sizing units](../css#sizing-units)) -- - The [Tailwind documentation](https://tailwindcss.com/docs) is searchable and contains a complete reference for every class. --- name: separation # Separation of Concerns? -- ## The traditional principle In the traditional approach to [web architecture](../../software-engineering/slides/web-architecture#separation-of-concerns), we are taught that the three core front-end technologies each have a distinct purpose: -- - **HTML** controls the _content_ of the page. -- - **CSS** controls the _presentation_ of that content. -- - **JavaScript** controls the _behavior_ of the page. -- - Traditionally, each of these "_concerns_" lives in its own separate file, or at least in its own separate block of code. Changing the look of a page should mean editing only the CSS file, not the HTML. -- - This idea is called **separation of concerns**, and for decades it has been considered a best practice in software engineering. --- template: separation ## Tailwind appears to break the rule At first glance, Tailwind looks like it _violates_ the separation of concerns principle. ```html
Sign up
``` -- ```html
Sign up
``` -- - In the Tailwind version, the styling lives _inside_ the HTML, mixed in with the content. Many traditionalists find this objectionable. --- template: separation ## Tailwind's counter-argument [The creators of Tailwind argue](https://adamwathan.me/css-utility-classes-and-separation-of-concerns/) that the traditional view _misunderstands_ what "separation of concerns" really means. -- - They observe that, in practice, **HTML and its visual styling are not actually independent of each other**. -- - When you change a button from a row of icons to a vertical list, you almost always have to change _both_ the HTML structure _and_ its CSS together. -- - If two things _always change together_, they are not really separate concerns - they are **one concern split across two files**. -- - True separation of concerns, the argument goes, is about decoupling things that _change independently_ - not about which file each line of code lives in. --- template: separation ## A different kind of separation Tailwind proposes a different boundary line between concerns: -- - The **content** (the words, links, and images) is one concern - it lives in HTML. -- - The **appearance of a particular component** (this button, this card, this navbar) is another concern - and it lives _alongside_ the HTML for that component. -- - The **design system itself** (what counts as "blue-500", what spacing values are allowed) is a third concern - it lives in Tailwind's configuration. -- - By colocating a component's HTML and styling, you can read, copy, or change a whole component in one place - without hunting through a separate CSS file. --- template: separation ## Honest tradeoffs Neither approach is universally "correct." Each has real benefits and real costs. -- **Advantages of utility-first (Tailwind):** - A component's look and structure are visible together. - Changing one component cannot accidentally break another, because there are no shared CSS class names. - Less custom CSS is written overall, so production CSS files are very small. -- **Advantages of separated CSS (traditional):** - HTML stays clean and easy to read, especially for non-programmers. - Repeated styles only need to be written once in a shared class. - The visual design can be redone without touching the HTML at all. -- - Reasonable, experienced developers disagree about which approach is better, and both are widely used in industry today. --- name: responsive-design # Responsive Design -- ## Concept Tailwind makes responsive design easy by letting you add a **prefix** to any utility class so that it only applies at certain browser widths. -- The prefixes correspond to the following breakpoints: -- - `sm:` applies at browser widths _>=640px_ (Small Devices) -- - `md:` applies at browser widths _>=768px_ (Medium Devices) -- - `lg:` applies at browser widths _>=1024px_ (Large Devices) -- - `xl:` applies at browser widths _>=1280px_ (Extra Large Devices) -- - `2xl:` applies at browser widths _>=1536px_ (Extra Extra Large Devices) -- - A class with no prefix applies at _all_ browser widths, including the smallest ones. --- template: responsive-design ## Usage For example, the following heading will be small on phones, larger on tablets, and largest on desktops. ```html
This heading grows with the screen!
``` -- - The approach is called **mobile-first** - you write the styles for the smallest screens first, then add prefixed versions that override them at larger sizes. -- - This pattern works for _any_ utility class - color, spacing, layout, sizing, and more. ```html
Background color changes with the screen size.
``` --- name: layout # Flex & Grid Layout -- ## Concept Tailwind provides utility classes for both **[flexbox](../css-layout#css-flexbox)** and **[CSS grid](../css-layout#css-grid)** - the two modern ways to lay out elements on a page. -- - You apply layout classes to a container element, and the children inside it are arranged automatically. -- - Like all utility classes, layout classes can be combined with responsive prefixes to create different layouts at different screen sizes. --- template: layout ## Flexbox Flexbox is great for arranging elements in a single row or column. ```html
First article
Second article
``` -- - `flex` turns the `div` into a flex container, so its children sit side by side. -- - `gap-4` adds space between the children. -- - `flex-1` tells each article to take up an equal share of the available width. -- - To stack them vertically on small screens but side-by-side on medium screens and larger, use a responsive prefix: ```html
First article
Second article
``` --- template: layout ## Grid For more complex layouts with rows and columns, use Tailwind's grid utilities. ```html
First article
Second article
``` -- - `grid` turns the container into a CSS grid. -- - `grid-cols-12` divides the container into 12 equal columns - just like Bootstrap's grid. -- - `col-span-6` makes each article take up 6 of those 12 columns - i.e. half the page. -- - And, of course, you can change column spans at different breakpoints: ```html
First article
Second article
``` --- template: layout ## Centering content A common task is centering content horizontally on the page. Tailwind makes this easy: ```html
My page content
Everything inside this div is centered with a maximum width.
``` -- - `max-w-4xl` sets a maximum width so the content does not stretch too wide on large screens. -- - `mx-auto` sets the left and right margins to `auto`, which centers the element horizontally. -- - `p-4` adds a little padding so the content does not touch the edges of the screen. --- name: customization # Interactivity & Customization -- ## State prefixes Tailwind makes it easy to change an element's style when the user interacts with it, again by using a **prefix** on a utility class. -- - `hover:` applies the style when the user hovers their mouse over the element. -- - `focus:` applies when the element is focused (e.g. a clicked input field). -- - `active:` applies when the element is being actively clicked. ```html
Hover over me!
``` -- - This button is blue normally, and turns a darker blue when the user hovers over it - no Javascript required. --- template: customization ## Going beyond the defaults Tailwind comes with sensible default colors, spacing values, and font sizes - but you can use any value you like by putting it in square brackets. ```html
Custom values for color, width, and font size.
``` -- - This is called an **arbitrary value**. It lets you escape the defaults whenever needed. Any CSS [sizing unit](../css#sizing-units) (`px`, `rem`, `vw`, `%`, etc.) can be used inside the brackets. -- - For most projects, however, the default values are designed to look good together and you will rarely need to use arbitrary values. --- name: alpine # Interactive Components with Alpine.js --- template: alpine ## Concept Tailwind itself ships **no JavaScript** - it is purely a CSS framework. To build rich interactive components like modals, dropdowns, accordions, and carousels, the Tailwind community standardly pairs Tailwind with [**Alpine.js**](https://alpinejs.dev). -- - Alpine.js is a tiny (~15 KB) JavaScript framework designed to be _sprinkled directly into your HTML_ - the same colocation philosophy as Tailwind's utility classes. -- - The simple `hover:` and `focus:` interactivity [customization](#customization) still applies for things that respond directly to the mouse or keyboard. -- - Alpine is for behaviors that need to **remember state** - for example, "is this menu currently open?", "which slide is the carousel showing?", or "has the user dismissed this dialog?". --- template: alpine ## Installation Just like Tailwind, Alpine.js can be added to a web page with a **single line of code** - no terminal commands, no installations, no setup files. -- - Add the following `script` tag to the `head` element of your HTML document, alongside the Tailwind script. ```html
My Tailwind + Alpine Page
``` -- - The `defer` attribute on the Alpine script tells the browser to wait until the page's HTML has finished loading before running Alpine - this is important. --- template: alpine ## Alpine basics Just three core "directives" (special HTML attributes) are enough to build most interactive components: -- - **`x-data="{ ... }"`** declares a small piece of _state_ on an element. The state is a JavaScript object, written in curly braces. -- - **`x-show="..."`** shows or hides an element based on a state expression. If the expression is true, the element appears; if false, it disappears. -- - **`@click="..."`** (a shorthand for `x-on:click`) runs a small JavaScript expression when the element is clicked. -- - A few other helpful directives you will see in the examples that follow: - `@mouseenter` and `@mouseleave` - run code when the mouse enters or leaves an element. - `x-transition` - fade things in and out smoothly when they show or hide. - `:src`, `:class`, etc. - shorthand for `x-bind:src`, `x-bind:class`, used to make HTML attributes reactive to state. --- template: alpine ## Example: Dropdown menu A button that toggles a dropdown menu open and closed. ```html
Menu
Home
About
Contact
``` -- - The button flips `open` between `true` and `false` each time it is clicked. -- - The `@click.outside` modifier is a convenience: it automatically closes the menu when the user clicks anywhere _else_ on the page. --- template: alpine ## Example: Modal dialog A pop-up dialog with a dimmed backdrop. ```html
Open dialog
Hello!
This is a modal dialog.
Close
``` -- - `fixed inset-0` makes the backdrop cover the entire window. -- - `bg-black/50` is a semi-transparent black, dimming the page behind the dialog. -- - `x-transition` fades the dialog in and out instead of snapping it on and off. --- template: alpine ## Example: Tooltip A small message that appears when the user hovers over an element. ```html
Hover me
Helpful hint!
``` -- - A pure-CSS tooltip is also possible with Tailwind's `group-hover:` modifier, but Alpine generalizes naturally to more complex tooltips - e.g. delayed appearance, click-to-dismiss, or content that depends on what the user has already done on the page. --- template: alpine ## Example: Accordion / collapsible A section of content that can be expanded and collapsed - the equivalent of Bootstrap's "collapse" component. ```html
Click to expand
Hidden content revealed! You can put anything in here - paragraphs, lists, images, even other Alpine components.
``` -- - This same pattern scales to a list of accordion items - just repeat the outer `div` once per item, each with its own `x-data`. --- template: alpine ## Example: Image carousel A slideshow of images with previous/next buttons. ```html
‹
›
``` -- - The state holds both _which_ slide is currently shown (`current`) and the _list_ of available slides (`images`). -- - The shorthand `:src` (for `x-bind:src`) makes the `img` tag's `src` attribute automatically update whenever `current` changes. -- - The `% images.length` math makes the slideshow wrap around from the last image back to the first one. --- template: alpine ## Example: Responsive navigation bar A common site-wide pattern: a horizontal navigation bar that becomes a "hamburger" menu on small screens. This is the example that combines _almost everything_ we have seen so far - utility classes, responsive prefixes, and Alpine state. ```html
My Site
☰
Home
About
Contact
``` -- - The key trick is the **`md:hidden`** and **`md:flex`** pair of responsive prefixes - they toggle visibility based on screen width, _independently_ of Alpine's state. -- - Alpine's `menuOpen` state only controls the dropdown on **small** screens. On medium and larger screens, `md:!block` overrides Alpine's choice and the links are always visible. (The `!` makes the utility important so it wins over the `hidden` class.) -- - This pattern - "Alpine state for small screens, Tailwind responsive utilities for larger ones" - is how nearly every Tailwind-based site builds its main navigation. --- template: alpine ## Where to go from here The examples above can be adapted into a wide range of interactive components, but Alpine.js offers many more features (lists, forms, animations) - explore the [Alpine documentation](https://alpinejs.dev) for the full reference. -- - As a general plan of action, copy each example _exactly_ from the documentation, make sure it works in your own page, and only _then_ customize it. -- - If you would rather use a library of pre-built Tailwind components than build your own with Alpine, several free options exist: - [Flowbite](https://flowbite.com) - a Bootstrap-style component library built on Tailwind, also CDN-loadable. - [Preline UI](https://preline.co) - a similar free component library with a large catalog. - [Tailwind UI](https://tailwindui.com) - the official, commercial collection from the Tailwind team. --- name: conclusions # Conclusions -- You have now seen the joy of the Tailwind CSS front-end framework. -- - With a single script tag, you have access to a complete modern styling system. -- - By combining small utility classes, you can build any design you can imagine - responsive, interactive, and clean - without writing custom CSS. -- - Thank you. Bye.