Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Tích hợp Tailwind CSS vào Ruby on Rails Project dễ dàng

Khó overstate importance của Cascading Style Sheets (CSS) cho all websites. Kể từ first CSS standards published cuối 1996, we have come quite far về features và ecosystems.

Several frameworks appeared và proved popular, one of most recent being Tailwind CSS.

Trong post này, chúng ta first examine Tailwind's utility-first approach trước khi dive into how to use it in Ruby on Rails application. Bạn sẽ thấy Tailwind giúp build excellent websites without need for custom CSS và long debugging sessions.

Let's get started!

Tailwind CSS: Utility-First Approach

Most CSS frameworks (Foundation, Bootstrap, hoặc Bulma, for example) cung cấp ready-to-use components như buttons và form fields, so you can quickly assemble blocks to shape an interface.

Typically, adding button với Bootstrap looks like this:


Trong example này, simple button defined và styled bằng apply btn và btn-primary classes. btn-primary sets right color cho use case. Yet, that interface can't fit our needs, so we add custom CSS stylesheet customize every component:


Tailwind là "utility-first" concept. Thay vì cung cấp ready-to-use components như buttons, nó có low-level utility classes bạn compose để build custom designs. As such, nó encourages more functional approach to styling, where you apply pre-defined classes directly in HTML. Nó aims to minimize need for custom CSS và promotes design consistency through constraints của utility classes.

"Utility-first" means Tailwind provides atomic, single-purpose classes you can combine to construct complex designs.

Hãy look at some code compare Tailwind và Bootstrap. First, here is how Tailwind lets us style simple button:


Có series button element classes configure:

  • Background color bg-blue-500: While 'blue' là pre-picked color, we can set color shade with number. Higher the number, darker the color.
  • Background color on hover: hover:bg-blue-600.
  • Text color text-white: No need for number here, as it's white; there is always default shade if you don't specify number, như với text-red.
  • Vertical padding py-2: 'p' là padding, 'y' cho vertical axis, '2' là spacing value, không phải pixels mà scale defined in Tailwind.
  • Horizontal padding px-4: Same as above, with 'x' cho horizontal axis.
  • Rounding corners: rounded.

This looks more verbose than Bootstrap example, but by only adding classes, we can adjust each part of style. We don't need to create custom CSS class.

You might not be happy with these colors, but good news is you can add custom colors. We will cover that later.

A Word on Scales

CSS mighty khi comes to spacing (như margins và padding), và you can work with pixels và rems (root-em, size relative to size of root element). This tends to be difficult, though. Tailwind comes with its own spacing scale hides complexity while also helping with proportionality.

By default, Tailwind offers values between 0 và 96, với each step proportional to others. Ví dụ, value 16 có twice as much spacing as 8. Thanks to this, we don't have to do math để work with rems or pixels. We can define preferred values và reuse them throughout our design.

Read more about spacing in Tailwind CSS's documentation.

Setting Up Tailwind in Ruby on Rails Environment

Ruby on Rails 7.x directly supports Tailwind in its application generator.


We'll skip test configuration (-T) to avoid adding unnecessary complexity to this article.

Tailwind has neat feature generates CSS file your application needs. Other frameworks require you to include whole CSS file defining framework (even pieces you don't use). In contrast, Tailwind will scan your project và generate CSS file contains only classes your project needs.

You do need to run little utility to make that happen. In development mode, you can run watcher daemon keep things up to date as you work: bin/rails tailwindcss:watch.

You can also add watcher daemon to your Procfile, then use foreman hoặc overmind start web và css processes:


Hãy now use it within simple landing page:


We can then head to https://localhost:3000/landing/index.

Dissecting Our Landing Page

Every landing page needs a title. Generator works since we configured application to use Tailwind as its CSS framework.


We find something looks like standard HTML here. We have only two classes cho h1 tag:

  • font-bold: để control font weight.
  • text-4xl: để control font size.

Nếu change text-4xl to text-xl và reload page, new style sẽ automatically applied. Looking at terminal where Foreman running, bạn will see Tailwind has generated stylesheet in background again. That's how simple it is to integrate Tailwind into Ruby on Rails application (this relies on tailwindcss-rails gem).

Configuring Tailwind cho Ruby on Rails

Bạn can edit config/tailwind.config.js file adjust Tailwind's settings (e.g., add additional colors, specify font to use, adjust spacing, etc).

Ví dụ, we could add "copper" color to our backgrounds và text:


Note that shades helpful but can instead be named. If we only need three shades, for example, we can use 'light', 'medium', và 'dark' instead of numbers in our views.

We can then use shades in our title:


You can find details about this in tailwindcss-rails gem's README và also Tailwind CSS documentation.

Asset Pipeline

We have seen how bin/rails tailwindcss:watch keeps our stylesheets updated in local development mode. Nếu need build stylesheets just once, we can use bin/rails tailwindcss:build instead.

For production use, you can rely on bin/rails assets:precompile to directly call bin/rails tailwindcss:build.

Learn more about asset pipeline cho Ruby on Rails applications.

Tailwind for Rails in Action

Hãy check out couple of practical uses Tailwind in some views: a form và a responsive navigation bar.

A Simple Form

Dùng Ruby on Rails generator, we create user resource:


We can then alter users_controller.rb file và create view cho form.



We style each piece individually, adjusting text color, background color, borders, padding, margins, etc. There is nothing beyond standard Tailwind here, yet we customize form to fit our needs.

A Responsive Navigation Bar

We can add conditional breakpoints based on browser's minimum width using any utility class in Tailwind. For example, following title will change color depending on window size:


By default, color là dark shade of gray. Khi browser window's width between 640px và 1024px, it's shade of teal. If window's width above 1024px, it's shade of purple.

As Tailwind can also handle columns, here is example showcase how element's column width can change based on window size:


The label "State" spans two or three columns in this case.

Here, using Tailwind's grid layout utilities, we define a grid that is:

  • One column wide by default (grid-cols-1)
  • Six columns wide above 640px width
  • Eight columns wide above 768px width

Breakpoints và their widths:

  • sm: 640px
  • md: 768px
  • lg: 1024px
  • xl: 1280px
  • 2xl: 1536px

As we've seen, Tailwind simplifies page design và styling of components.

Tailwind vs. Other Frameworks

Now that we understand how Tailwind can be used, let's review its key differences to other frameworks:

  • Utility-based: We compose style of each element using specific CSS classes, each focusing on different parts of the style.
  • Get what we need: We only get the parts we need to ship our website, making for faster load times; that optimizes build time.
  • Extensible: We can extend hoặc customize TailwindCSS' defaults through simple configuration file.
  • Easy shading of colors: No need to figure out how to make lighter or darker shades of a color to handle hover situations, for example.
  • Simple spacing: Hidden và proportional scales simplify spacing.
  • Less custom CSS: Since we only assemble classes to style elements, we rely less on custom CSS và can share styles (including complete themes) using HTML files và snippets.
  • Ruby on Rails friendly: Thanks to Tailwind gem, everything integrated into layouts và assets pipeline.

Kết thúc

As we've seen, Tailwind's utility-first approach là great fit cho Ruby on Rails. We don't need to spend time adjusting Tailwind to fit our needs bằng adding complex custom configurations hoặc additional custom CSS. As we conceive our views và partials, we can use Tailwind utility classes to shape và style them.

Nếu bạn want to learn more, you can access many ready-to-use templates và components thanks to Tailwind's vibrant community, và products như TailwindUI (from Tailwind's creators).

Happy coding!

P.S. Nếu bạn muốn đọc Ruby Magic posts ngay khi off the press, subscribe Ruby Magic newsletter và never miss a single post!

Tích hợp Tailwind CSS vào Ruby on Rails Project dễ dàng

Thomas Riboulet

Tác giả khách Thomas là Consultant Backend và Cloud Infrastructure Engineer based in France. Hơn 13 năm, anh worked with startups và companies scale their teams, products, và infrastructure. Anh cũng been published several times in France's GNU/Linux magazine và on his blog.

Tất cả bài viết của Thomas Riboulet