Using CSS Styles with the Rails Asset Pipeline
Learn how to use the Rails Asset pipeline to customize CSS styles throughout your Rails application.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

To integrate CSS with your application, you need to learn how to use the css and scss files in the Rails asset pipeline.

To start, go to app/assets/stylesheets and you'll see there are already four files here by default. The first is application.css and in this file, we'll have all the different CSS files that will be combined together at compile time. This is how this file looks.

large

If you go to line #13, you'll see a call to require_tree .. This means every one of the other scss files in the stylesheets folder will get called and will be compiled into a single CSS file when the application runs. The obvious advantage is you don't have to put all your styles into this file, but you can organize them how you want, and yet they will all be compiled together just like how you would want it to.

Next, line #14 has a call to require_self, and this applies the style to the entire application. You can choose what to put in here, and accordingly it will be applied to all the pages.

For example, I'm going to add

body {
  margin: 42px;
}

medium

This change is reflected in my home page, as you can see a little margin on all the sides.

medium

For cleaner code, I prefer to create a new css file and put this code in it.

body {
  margin: 42px;
}

This code will anyway get called by the require_tree ., so there will be no change to our home page.

Now, if you want to apply some custom styles to the home page, go to pages.scss For this example, I'm going to create a new class:

.homepage-projects p {
  font-size: 1.25em;
}

The above code tells the CSS generator to set the font-size for all the paragraph tags inside homepage-projects.
Next, I go to my home page, which is home.html.erb' and here, I add adiv` class.

<div class="homepage-projects">
</div>

My home page should be like this.

medium

If you see, the shared/projects partial has a paragraph tag, and we are telling the framework to set the font-size for these paragraph tags, and this exactly what it does.
Next, go to scaffolds.scss file and you can see it contains a lot of CSS code.

large

If you don't like any of this style, you can delete them. Personally, I don't like these default styles, so I delete them first and use Bootstrap or Foundation CSS framework. However, you can use these styles or modify them based on your preference.

In the next lesson, you can see how to use custom fonts within the Rails asset pipeline.