JavaScript and React course · Module 7: Styling and Animations

Tailwind CSS - Cosmic Styling Efficiency

5 min read
In this lesson9

On our cosmic journey through the React galaxy, we arrive at one of the most revolutionary technologies of recent years - Tailwind CSS. It is like discovering advanced, high-performance alien technology that completely changes how we build user interfaces.

What is Tailwind CSS?

Tailwind CSS is a CSS framework based on the utility-first approach, which involves composing interfaces by applying utility classes directly in HTML/JSX code. Instead of writing your own CSS styles, you use ready-made classes that represent individual CSS properties.

Imagine that each Tailwind class is like a small spaceship component - independent, specialized, and ready for immediate use. Combined together, they form a fully functional, personalized spaceship (interface) exactly as you need it.

Installing and Configuring Tailwind CSS in a React Project

To start your adventure with Tailwind CSS in a React project, follow these steps:

1# Installing Tailwind CSS and its dependencies
2npm install -D tailwindcss postcss autoprefixer
3npx tailwindcss init -p

The above commands install Tailwind CSS along with the necessary dependencies and create basic configuration files: tailwind.config.js and postcss.config.js.

Next, edit the tailwind.config.js file:

1/** @type {import('tailwindcss').Config} */
2module.exports = {
3  content: [
4    "./src/**/*.{js,jsx,ts,tsx}",
5  ],
6  theme: {
7    extend: {},
8  },
9  plugins: [],
10}

Finally, add Tailwind directives to your main CSS file:

1/* index.css */
2@tailwind base;
3@tailwind components;
4@tailwind utilities;

Basics of Using Tailwind CSS

Styling components with Tailwind CSS is like building with blocks. Each class represents one specific CSS property. Let's see how to create a button:

1function SpaceButton() {
2  return (
3    <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded transition duration-300">
4      Activate hyperdrive
5    </button>
6  );
7}

In the example above:

  • bg-blue-500 - blue background (scale 500)
  • hover:bg-blue-700 - background color on hover
  • text-white - white text
  • font-bold - bold text
  • py-2 px-4 - padding: 0.5rem top and bottom, 1rem left and right
  • rounded - rounded corners
  • transition duration-300 - smooth animation lasting 300ms

Responsiveness with Tailwind CSS

Tailwind offers an intuitive modifier system for different breakpoints. Imagine that your cosmic interface needs to adapt to different display devices - from small control panels to enormous command center screens.

1<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
2  <div className="bg-gray-100 p-4 rounded">Panel 1</div>
3  <div className="bg-gray-100 p-4 rounded">Panel 2</div>
4  <div className="bg-gray-100 p-4 rounded">Panel 3</div>
5</div>

In this example:

  • On small screens we have 1 column
  • On medium screens (md:) we have 2 columns
  • On large screens (lg:) we have 3 columns

Custom Styles and Class Composition

Extending the Theme

You can customize colors, fonts, breakpoints, and other aspects of Tailwind for your project by editing the tailwind.config.js file:

1module.exports = {
2  theme: {
3    extend: {
4      colors: {
5        'space-blue': '#1a2b3c',
6        'cosmic-purple': '#7209b7',
7        'stellar-red': '#f72585',
8      },
9      fontFamily: {
10        'futuristic': ['Space Grotesk', 'sans-serif'],
11      },
12      spacing: {
13        '128': '32rem',
14      },
15    },
16  },
17  // ...remaining configuration
18}

Composing Classes with @apply

For recurring class combinations, Tailwind offers the @apply directive, which lets you create your own composite classes:

1/* index.css */
2@tailwind base;
3@tailwind components;
4
5@layer components {
6  .space-button {
7    @apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded transition duration-300;
8  }
9
10  .planet-card {
11    @apply bg-gray-800 text-white p-6 rounded-lg shadow-lg hover:shadow-xl transition-shadow;
12  }
13}
14
15@tailwind utilities;

Now you can use these classes in your components:

1<button className="space-button">Start mission</button>
2<div className="planet-card">
3  <h3>Mars</h3>
4  <p>The red planet</p>
5</div>

Advantages of Tailwind CSS

  1. Development speed - You do not need to switch between CSS and JSX files, everything is in one place.

  2. Low bundle size growth - Thanks to PurgeCSS, the final CSS file contains only used classes.

  3. Project consistency - Predefined color scales, sizes, etc. enforce consistency.

  4. Responsiveness - An intuitive breakpoint system makes creating responsive interfaces easier.

  5. Easy collaboration - Developers work within the same system, leading to more consistent code.

When to Use Tailwind CSS?

Tailwind is ideal for:

  • Projects where you value development speed
  • Applications that need a consistent design system
  • Teams that want to avoid CSS conflicts
  • Situations when you want to avoid inventing class names

Integration with Other Tools and Frameworks

Tailwind integrates well with other tools and libraries. You can use it together with:

  • Styled Components - via the tailwind-styled-components plugin
  • Material UI or Chakra UI - as a complement for more specific styles
  • Framer Motion - adding animations to Tailwind-styled elements

Practical Exercise: Create a Cosmic Cockpit Interface

Use Tailwind CSS to create a responsive cosmic cockpit interface containing:

  1. A header with the mission logo and navigation menu
  2. A control panel with buttons and indicators
  3. A monitoring section with data in card form
  4. A footer with mission information

Remember about responsiveness and using different Tailwind components such as flex, grid, cards, buttons, etc.

This exercise will let you explore the cosmic world of utility-first CSS and understand how Tailwind CSS can accelerate your journey through the galaxy of frontend development.

Code for this lesson: App.jsx
1import React, { useState } from 'react';
2import './styles.css';
3
4// Simulating Tailwind CSS using standard classes
5// In a real project you would use the full Tailwind CSS
6
7function SpaceDashboard() {
8  const [selectedPlanet, setSelectedPlanet] = useState(null);
9
10  const planets = [
11    { id: 1, name: 'Mars', distance: '225 million km', temp: '-60°C', moons: 2 },
12    { id: 2, name: 'Jupiter', distance: '778 million km', temp: '-110°C', moons: 79 },
13    { id: 3, name: 'Saturn', distance: '1.4 billion km', temp: '-140°C', moons: 82 },
14    { id: 4, name: 'Uranus', distance: '2.9 billion km', temp: '-195°C', moons: 27 },
15  ];
16
17  return (
18    <div className="min-h-screen bg-gradient-to-br from-gray-900 via-purple-900 to-gray-900 p-6">
19      {/* Header */}
20      <header className="text-center mb-12">
21        <h1 className="text-4xl font-bold text-cyan-400 mb-2">
22          Solar System Explorer
23        </h1>
24        <p className="text-gray-400">
25          Utility-First CSS with Tailwind classes
26        </p>
27      </header>
28
29      {/* Planet grid */}
30      <div className="max-w-6xl mx-auto grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
31        {planets.map(planet => (
32          <div
33            key={planet.id}
34            onClick={() => setSelectedPlanet(planet)}
35            className={`
36              bg-white/5 backdrop-blur-sm rounded-xl p-6
37              border border-white/10 cursor-pointer
38              transition-all duration-300 hover:scale-105
39              hover:border-cyan-500/50 hover:shadow-lg hover:shadow-cyan-500/20
40              ${selectedPlanet?.id === planet.id ? 'ring-2 ring-cyan-400' : ''}
41            `}
42          >
43            <h3 className="text-xl font-bold text-yellow-400 mb-4">
44              {planet.name}
45            </h3>
46
47            <div className="space-y-2 text-sm">
48              <div className="flex justify-between">
49                <span className="text-gray-400">Distance:</span>
50                <span className="text-white">{planet.distance}</span>
51              </div>
52              <div className="flex justify-between">
53                <span className="text-gray-400">Temperature:</span>
54                <span className="text-cyan-300">{planet.temp}</span>
55              </div>
56              <div className="flex justify-between">
57                <span className="text-gray-400">Moons:</span>
58                <span className="text-white">{planet.moons}</span>
59              </div>
60            </div>
61          </div>
62        ))}
63      </div>
64
65      {/* Details panel */}
66      {selectedPlanet && (
67        <div className="max-w-2xl mx-auto bg-white/5 backdrop-blur-sm rounded-xl p-8 border border-cyan-500/30">
68          <h2 className="text-2xl font-bold text-cyan-400 mb-4">
69            Details: {selectedPlanet.name}
70          </h2>
71
72          <div className="grid grid-cols-2 gap-4 mb-6">
73            <div className="bg-white/5 rounded-lg p-4">
74              <p className="text-gray-400 text-sm">Distance from the Sun</p>
75              <p className="text-2xl font-bold text-white">{selectedPlanet.distance}</p>
76            </div>
77            <div className="bg-white/5 rounded-lg p-4">
78              <p className="text-gray-400 text-sm">Average temperature</p>
79              <p className="text-2xl font-bold text-cyan-300">{selectedPlanet.temp}</p>
80            </div>
81          </div>
82
83          <div className="flex gap-4">
84            <button className="flex-1 bg-cyan-500 hover:bg-cyan-600 text-black font-bold py-3 px-6 rounded-lg transition-colors">
85              Schedule mission
86            </button>
87            <button className="flex-1 bg-transparent border-2 border-yellow-500 text-yellow-500 hover:bg-yellow-500/10 font-bold py-3 px-6 rounded-lg transition-colors">
88              More information
89            </button>
90          </div>
91        </div>
92      )}
93
94      {/* Footer */}
95      <footer className="text-center mt-12 text-gray-500 text-sm">
96        <p>Tailwind CSS lets you build interfaces using utility classes</p>
97        <p className="mt-1">without writing your own CSS</p>
98      </footer>
99    </div>
100  );
101}
102
103export default SpaceDashboard;

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which CSS unit is best for creating responsive font sizes?

  2. 2. Which approach to breakpoints is recommended in responsive design?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Responsive Design with SCSS

Useful articles