DEV Community

thomasvanholder
thomasvanholder

Posted on

Import Class in Relative File into Tailwind CSS and Rails

To import a relative CSS file into Tailwind, the postcss-import is required.

  1. Install postcss-import
  2. Add postcss-config file
  3. Add postcss to build script
  4. Create a button class
  5. Swap tailwind directive for import
  6. Extract button class into seperate file

1. Install postcss-import

yarn add postcss-import
Enter fullscreen mode Exit fullscreen mode

2. Add postcss.config.file

postcss.config.js
module.exports = {
  plugins: [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
  ]
}
Enter fullscreen mode Exit fullscreen mode

3. Add postcss to build:css script

In package.json add --postcss

old

{
  "scripts": {
    "build:css": "tailwindcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css"
  }
}
Enter fullscreen mode Exit fullscreen mode

new

{
  "scripts": {
    "build:css": "tailwindcss --postcss -i ./app/assets/stylesheets/application.tailwind.css -o ./app/assets/builds/application.css"
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Create a button class

Add a button component in application.tailwind.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .btn-blue {
    @apply text-white bg-blue-500 rounded-lg hover:bg-blue-700;
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's see it we get a blue button

 <button type="button" class="btn-blue">Save</button>
Enter fullscreen mode Exit fullscreen mode

5. Swap tailwind directive for import

/* old */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* new */
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
Enter fullscreen mode Exit fullscreen mode

6. Extract button class into seperate file

in application.tailwind.css

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "./components/buttons.css";
@import "tailwindcss/utilities";
Enter fullscreen mode Exit fullscreen mode

in ./components/buttons.css

@layer components {
  .btn-blue {
    @apply text-white bg-blue-500 rounded-lg hover:bg-blue-700;
  }
}
Enter fullscreen mode Exit fullscreen mode

A few notes from the Tailwind docs:

  • Don't mix custom css and imports in the same file
  • Wrap custom css in @layer components to avoid specificity issues

Top comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
thomasvanholder profile image
thomasvanholder

Hi Hanifa, you can surely import relative files in PHP too. As I don't code in PHP, I can't help you with the specific set-up instructions.