Styling Your Application
8 min read
Styling Your Remix Application π¨
Welcome to the wonderful world of styling in Remix! You've built the structure, now it's time to make it shine. Styling is more than just colors and fonts; it's about creating a user experience that's intuitive, engaging, and just plain pleasant to look at.
The Problem: In the Wild West of web development, managing CSS can become a tangled mess. You might have one giant stylesheet for your entire application, leading to selector conflicts, unused styles, and a general sense of dread when you need to make a change. It's like trying to find a specific book in a library where all the books are thrown in one big pile.
The Remix Solution: Remix brings order to this chaos by embracing a route-based styling approach. This means that styles are loaded only for the specific routes that need them, keeping your application lean and your CSS organized. Itβs like each section of your library has its own neatly organized shelves.
1. The links Function: Injecting Stylesheets Automatically
Let's start with the magical gateway for all your styling needs in Remix: the links function.
The Problem: How do you tell a specific page in your application which stylesheet to use? In traditional web development, you might manually add <link> tags to the <head> of your HTML files. But in a dynamic application like one built with Remix, this can get complicated and inefficient.
The links Function to the Rescue: Remix provides a special function called links that you can export from your route files. This function returns an array of objects, where each object represents a <link> tag to be injected into the document's <head>.
Imagine you're the director of a play. For each scene (route), you tell the stage crew (Remix) exactly which props and backdrops (stylesheets) are needed. The links function is your script for doing just that.
How it Works:
When you navigate to a route, Remix calls its links function and adds the specified links to the page. When you navigate away, it removes them. Simple and brilliant!
Example:
Let's say you have a stylesheet for your dashboard route.
In app/routes/dashboard.tsx:
import type { LinksFunction } from "@remix-run/node";
import dashboardStyles from "~/styles/dashboard.css";
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: dashboardStyles },
];
export default function Dashboard() {
return (
<div className="dashboard-container">
<h1>Welcome to your Dashboard!</h1>
{/* Your dashboard content */}
</div>
);
}Under the Hood: Remix's server-side rendering capabilities mean that the initial HTML sent to the browser already includes the necessary <link> tags. This avoids the dreaded "flash of unstyled content" and makes your application feel faster.
Fun Fact: The links function isn't just for stylesheets! You can also use it to add other <link> tags, like favicons or preloading resources.
2. Traditional CSS and CSS Modules Integration
Sometimes, you just want to write good old-fashioned CSS. And you know what? Remix is totally cool with that.
The Problem: How do you prevent your CSS class names from clashing with each other, especially in a large application? If you have a .card class in one part of your app and another .card class in a different part, they could unintentionally affect each other's styles.
Solution Part 1: Traditional CSS:
You can absolutely use plain CSS files. The links function makes it easy to scope these styles to specific routes. This already reduces the chances of conflicts because only the CSS for the current and parent routes will be active.
Example:
In app/styles/global.css:
body {
font-family: sans-serif;
}In app/root.tsx:
import type { LinksFunction } from "@remix-run/node";
import globalStyles from "~/styles/global.css";
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: globalStyles },
];
// ... rest of your root componentSolution Part 2: CSS Modules for True Scoping:
For even more robust scoping, you can use CSS Modules. This is a fantastic way to write CSS that is locally scoped to a specific component.
How it Works:
With CSS Modules, when you import a CSS file into your component, you get a JavaScript object that maps your class names to unique, generated class names. This ensures that your styles will never conflict with other styles in your application. It's like giving every component its own private, soundproof styling booth.
Example:
In app/components/Button.module.css:
.button {
background-color: blue;
color: white;
padding: 10px 20px;
}In app/components/Button.tsx:
import styles from "./Button.module.css";
export default function Button() {
return <button className={styles.button}>Click Me</button>;
}When this renders, the button will have a class like Button_button__a4X9gs, which is highly unlikely to clash with anything else.
Important Note: To use features like CSS Modules that bundle CSS into a single file, you'll need to import the CSS bundle in your app/root.tsx.
import { cssBundleHref } from "@remix-run/css-bundle";
import type { LinksFunction } from "@remix-run/node";
export const links: LinksFunction = () => [
...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []),
];3. Utility-First: Setting Up and Using Tailwind CSS with Remix
If you love the speed and consistency of utility-first CSS, you'll be happy to know that setting up Tailwind CSS with Remix is a breeze.
The Problem: Writing custom CSS for every little thing can be time-consuming. You end up with a lot of CSS files and have to constantly switch between your markup and your styles.
The Tailwind CSS Solution:
Tailwind CSS provides a set of pre-defined utility classes that you can apply directly in your HTML. This allows you to build complex designs without ever leaving your markup. It's like having a well-organized toolbox with every tool you could possibly need right at your fingertips.
Getting Started with Tailwind CSS in Remix:
Install Dependencies:
You'll need to installtailwindcss,postcss, andautoprefixer.bashnpm install -D tailwindcss postcss autoprefixerInitialize Tailwind CSS:
This command will create atailwind.config.jsfile in your project root.bashnpx tailwindcss initConfigure your
tailwind.config.js:
You need to tell Tailwind where to look for your template files.javascript/** @type {import('tailwindcss').Config} */ export default { content: ["./app/**/*.{js,jsx,ts,tsx}"], theme: { extend: {}, }, plugins: [], };Create a Tailwind CSS file:
In yourappdirectory, create a file namedtailwind.cssand add the@tailwinddirectives.css@tailwind base; @tailwind components; @tailwind utilities;Import the CSS file:
In yourapp/root.tsx, import thetailwind.cssfile and add it to yourlinksfunction.typescriptimport type { LinksFunction } from "@remix-run/node"; import tailwindStyles from "./tailwind.css"; export const links: LinksFunction = () => [ { rel: "stylesheet", href: tailwindStyles }, ];Update your
package.jsonscripts:
You'll need to add a script to process your Tailwind CSS.json"scripts": { "build:css": "tailwindcss -o ./app/tailwind.css", "dev:css": "tailwindcss -o ./app/tailwind.css --watch" }And update your
devandbuildscripts to run the CSS scripts.json"dev": "concurrently \"npm run dev:css\" \"remix dev\"", "build": "npm run build:css && remix build"
Now you can start using Tailwind's utility classes in your components!
export default function MyComponent() {
return (
<h1 className="text-3xl font-bold underline text-blue-600">
Hello, Tailwind!
</h1>
);
}A Funny Exaggeration: Without Tailwind, you might feel like you're hand-carving every single button and input field from a block of wood. With Tailwind, you've got a state-of-the-art 3D printer for your UI.
4. Route-Specific Styling: Loading CSS Only When Required
One of Remix's superpowers is its ability to load only the CSS that's needed for the current view.
The Problem: Loading a massive, application-wide stylesheet on every page is inefficient. Your users are downloading styles for components they might never see, which can slow down the initial page load.
The Remix Approach:
By using the links function in each of your route files, you're naturally creating route-specific styling. When you navigate to a new route, Remix cleverly fetches and applies the new CSS, and unloads the old.
Real-Life Scenario: Imagine you're building an e-commerce site. The CSS for the product-heavy homepage is quite different from the minimalist checkout page. With Remix, a user visiting the homepage only downloads the homepage styles. When they proceed to checkout, the checkout-specific styles are loaded. This "just-in-time" styling makes for a much snappier user experience.
Nested Routes and Styling:
The beauty of Remix's nested routing is that styles cascade down. A parent route's styles are available to its children.
Example File Structure:
app/
βββ routes/
β βββ dashboard.tsx
β βββ dashboard/
β β βββ _index.tsx
β β βββ settings.tsxIn this case:
- Navigating to
/dashboardwill load the styles fromdashboard.tsxanddashboard/_index.tsx. - Navigating to
/dashboard/settingswill load the styles fromdashboard.tsxanddashboard/settings.tsx.
This predictable and organized system for loading styles is one of the things that makes developing with Remix such a joy.
Additional Resources:
- Remix Docs on Styling: https://remix.run/docs/en/main/styling
- Tailwind CSS with Remix: https://tailwindcss.com/docs/guides/remix
- Remix
linksfunction API: https://remix.run/docs/en/main/route/links
Challenge
Challenge: Implementing Route-Based Styling in Remix
You are tasked with setting up the styling for a multi-route Remix application. You will be working with three simplified route files: app/root.tsx, app/routes/dashboard.tsx, and app/routes/dashboard.reports.tsx.
Your goal is to correctly implement the links function in each file to load the appropriate stylesheets based on the active route, demonstrating your understanding of Remix's route-based styling, CSS bundling, and CSS Modules integration.
Requirements:
In
app/root.tsx:- Export a
linksfunction. - This function must return links for two stylesheets:
- A global stylesheet located at the path
/styles/global.css. - The stylesheet link for bundled CSS features, which is provided by the
cssBundleHrefimport.
- A global stylesheet located at the path
- Export a
In
app/routes/dashboard.tsx:- Export a
linksfunction. - It should link to a stylesheet specific to the dashboard layout, located at
/styles/dashboard.css.
- Export a
In
app/routes/dashboard.reports.tsx:- Export a
linksfunction. - It must link to the stylesheet from the imported CSS Module,
reportsStyles.
- Export a
Expected result
Your final code should contain the correct implementation of the links function in all three specified files. The functions should return an array of link descriptor objects as specified in the requirements.
Here is the expected code:
// FILE: app/root.tsx
import { cssBundleHref } from "@remix-run/css-bundle";
import type { LinksFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import globalStyles from "/styles/global.css";
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: globalStyles },
...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []),
];
export default function App() {
return (
<html>
<head>
{/* Remix will inject links here */}
</head>
<body>
<Outlet />
</body>
</html>
);
}
// =======================================================
// FILE: app/routes/dashboard.tsx
import type { LinksFunction } from "@remix-run/node";
import { Outlet } from "@remix-run/react";
import dashboardStyles from "/styles/dashboard.css";
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: dashboardStyles },
];
export default function DashboardLayout() {
return (
<main className="dashboard">
<h1>Dashboard</h1>
<Outlet />
</main>
);
}
// =======================================================
// FILE: app/routes/dashboard.reports.tsx
import type { LinksFunction } from "@remix-run/node";
import reportsStyles from "~/styles/reports.module.css";
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: reportsStyles },
];
export default function Reports() {
return (
<div className={reportsStyles.container}>
<h2>Reports Section</h2>
</div>
);
}