Muhammed Kanyi
Tailwind CSS with rails 7

CSS is amazing but can be time consuming to Build beautiful sites when writing your own CSS. There are many CSS libraries but recently Tailwind CSS is one of the top CSS library.

What is Tailwind CSS

Tailwindcss is a utility-first CSS framework for rapidly building custom user interfaces. It’s made to be super flexible and extensible, so that you can quickly build your projects on top of it, with no restrictions. Tailwind has been built with a developer’s mindset and includes many features out of the box to help you deal with repetitive CSS tasks so you can focus on delivering great experiences to your users

Installing Tailwind CSS alongside Rails

While it’s relatively straight forward to install Tailwind CSS with rails, sometimes you will run into some issues.

When creating a new rails app, you can pass the CSS argument to add Tailwind CSS configurations along Running the command

rails new tailwind_rails7 --css tailwind

Will create the tailwind.config.js which contains the Tailwind CSS configuration file you can make your personal configuration

<!-- config/tailwind.config.js -->
module.exports = {
  content: [
    './public/*.html',
    './app/helpers/**/*.rb',
    './app/javascript/**/*.js',
    './app/views/**/*.{erb,haml,html,slim}'
  ],
  theme: {
    extend: {
      fontFamily: {
        sans: ['Inter var', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  plugins: [
    require('@tailwindcss/forms'),
    require('@tailwindcss/aspect-ratio'),
    require('@tailwindcss/typography'),
  ]
}

Rails 7 also creates the application.tailwind.css file which is use to import the CSS

<!-- app/assets/stylesheets/application.tailwind.css -->
@tailwind base;
@tailwind components;
@tailwind utilities;

/*

@layer components {
  .btn-primary {
    @apply py-2 px-4 bg-blue-200;
  }
}

*/

In your application.html.erb Rails 8 adds the stylesheet_link_tag to render your tailwind css, This allows you to use your Apllication.css for writing custom styles

<!-- app/views/layouts/application.html.erb -->

   <!DOCTYPE html>
<html>
  <head>
    <title>TailwindRails7</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_importmap_tags %>
  </head>

  <body>
    <main class="container mx-auto mt-28 px-5 flex">
      <%= yield %>
    </main>
  </body>
</html>

Rails 7 uses foreman (bin/dev) in development to compile Tailwind CSS that will generates your styles on-demand as you author your templates instead of generating everything in advance at initial build time. This make sure your development and production environment are identical.

Leave a Reply

Your email address will not be published. Required fields are marked *