How to Add CSS in Ruby on Rails?
Last Updated :
02 May, 2024
This article focuses on discussing how to add Cascading Style Sheets (CSS) in Ruby on Rails.
Using SCSS
SCSS (Sass) is a preprocessor that extends CSS with features like variables, mixins, and nesting. These features make your stylesheets more maintainable, reusable, and easier to read.
1. Create SCSS File: Start by creating a new file with the .scss extension in the app/assets/stylesheets directory.
2. Import Bootstrap (Optional): If you're using Bootstrap for pre-built styles, import it into your SCSS file using @import "bootstrap";
3. Write SCSS Styles: Add your custom styles to the SCSS file. Utilize features like variables, mixins, and nesting for better organization:
application.scss
CSS
body {
font-family: "Arial", sans-serif;
background-color: #b6d3f1;
}
div {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
p {
font-size: 20px;
}
4. Link SCSS File: In your application layout file (usually app/views/layouts/application.html.erb), use the stylesheet_link_tag helper to link the SCSS file:
<%= stylesheet_link_tag 'application', media: 'all', data: { turbolinks: false } %>
Below example shows the content of app/views/layouts/application.html.erb:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Rails App with SCSS</title>
<%= stylesheet_link_tag 'application', media: 'all', data: { turbolinks: false } %>
</head>
<body>
<div>
<p>Welcome to Ruby and Rails application</p>
</div>
</body>
</html>
Output:
OutputUsing Plain CSS
While SCSS is generally preferred for its advanced features, you can also use plain CSS files.
1. Create CSS File: Create a new file with the .css extension in the app/assets/stylesheets directory (e.g., custom.css).
2. Write CSS Styles: Add your custom styles directly to the CSS file:
custom.css
CSS
body {
font-family: 'Arial', sans-serif;
background-color: #f8f9fa;
}
div {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.btn-primary {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border-radius: 5px;
}
3. Link CSS File: Link the CSS file in your application layout using the stylesheet_link_tag helper:
<%= stylesheet_link_tag 'custom', media: 'all', data: { turbolinks: false } %>
Below example shows the content of app/views/layouts/application.html.erb:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Rails App with Plain CSS</title>
<%= stylesheet_link_tag 'custom', media: 'all', data: { turbolinks: false } %>
</head>
<body>
<button class="btn-primary" >Click Me</button>
</body>
</html>
Output:
outputUsing Inline Styles
Alternatively, you can also apply styles directly within your HTML views using inline styles.
1. Write Inline Styles: Apply styles directly within your HTML views using the style attribute.
Below example shows inline styles in HTML view:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Inline Styles Example</title>
</head>
<body style="background-color: #f0f0f0;">
<h1 style="color: blue;">Welcome to my Rails application!</h1>
</body>
</html>
Output:
outputUsing External CSS Frameworks
Integrating external CSS frameworks like Bootstrap or Foundation can expedite styling and provide a consistent UI across your application.
- Install Framework: Install the desired framework via npm or include its CDN link in your application.
- Follow Framework Guidelines: Refer to the documentation of the chosen framework for instructions on usage and customization.
- Apply Framework Classes: Utilize pre-defined classes provided by the framework to style your elements.
You can install Bootstrap using npm or yarn
npm install bootstrap
Alternatively, you can include the Bootstrap CDN link directly in your application layout
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
Below example shows Bootstrap integration:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Rails App with Bootstrap</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container d-flex justify-content-center align-items-center min-vh-100">
<button class="btn-success btn-lg">Welcome to GFG</button>
</div>
</body>
</html>
Output:
OutputComparison of Different Approaches
Feature
| SCSS
| Plain CSS
| Inline Styles
| External CSS Frameworks
|
---|
Variables
| Yes (Improve maintainability)
| No
| No
| Yes (Framework-specific)
|
---|
Mixins
| Yes (Reusable code blocks)
| No
| No
| No
|
---|
Nesting
| Yes (Organize styles hierarchically)
| No
| No
| No
|
---|
Preprocessing
| Requires compilation step (Rails Asset Pipeline)
| No compilation needed
| No compilation needed
| No compilation needed
|
---|
Learning Curve
| Slightly steeper learning curve
| Easier to learn for beginners
| Easy to learn for beginners
| Varies based on framework
|
---|
Additional Considerations
- Asset Pipeline: Rails uses the Asset Pipeline to manage and compile SCSS/CSS files. The Asset Pipeline concatenates and minifies CSS files for production, improving performance.
- Turbolinks: Use data: { turbolinks: false } in the stylesheet_link_tag to prevent Turbolinks from interfering with CSS reloading during development.
Conclusion
By considering the differences between SCSS, plain CSS, inline styles, and external CSS frameworks, along with the specific needs of your project, you can make an informed decision on which method to use for styling your Ruby on Rails application.
Similar Reads
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline. Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the c
2 min read
How to Create Button in Ruby on Rails?
Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application's data, logic, and user interface components. Rails emphasizes convention over co
7 min read
How to create model in Ruby on Rails?
In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever
4 min read
How to Upload Files in Ruby on Rails?
Uploading files in a web application is a common requirement, whether it's for user profile pictures, documents, or any other files. Ruby on Rails makes this task straightforward with its built-in tools. In this article, we'll walk through the steps to set up file uploads in a Rails app, from creati
6 min read
How to create table in Ruby on Rails?
In Ruby on Rails, creating tables involves using migrations, which are a powerful mechanism for managing database schema changes. Here's a detailed breakdown of the process: 1. Database Setup (Optional): While APIs can function without databases, many Rails applications use them for data persistence
3 min read
Ruby on Rails - How to Send Emails?
Email communication is a must-have function for those who want their web application to keep up with the current trend. The Action Mailer Framework of Ruby on Rails helps to make the tasks of sending emails easier. This article focuses on discussing sending emails using Ruby on Rails. Table of Conte
11 min read
How to add new line in Ruby?
In Ruby, newlines (line breaks) play a crucial role in formatting and separating your code. Whether you're crafting clear error messages or building readable output, knowing how to add newlines is essential. Here's a breakdown of various methods you can use: 1. The Almighty `puts`:The built-in `puts
2 min read
How to Install Ruby on Rails on MacOS?
Ruby on Rails, also known as rails, is a server-side web application development framework written in the Ruby programming language. David Heinemeier Hansson developed it under the MIT License. It supports MVC (model-view-controller) architecture that provides a default structure for databases, web
2 min read
How to Install a local gem in Ruby?
Ruby is a high-level and open-source programming language. It is very useful in many aspects. For programming productivity and simplicity, the Ruby language is widely used. Like Java, Python, Ruby is nowadays a highly useful programming language. In Ruby, there is a package manager called Gems. It i
2 min read
How to Build an API With Ruby on Rails?
Ruby on Rails API refers to the application programming interface (API) framework provided by the Ruby on Rails (Rails) web application framework. It allows developers to build and expose APIs for their web applications efficiently. Ruby on Rails is a popular web development framework written in the
4 min read