Adding a Stylesheet to a Sinatra Application

Feature thumb snip20170922 7

If you're new to building applications with the Sinatra web application framework, you might be curious about how you can style the HTML pages. There are a couple options:

Using embedded or inline styles in the ERB files Calling an external stylesheet

Using embedded and inline styles is a relatively straightforward process, it's the same workflow that you'd follow for vanilla HTML. However there are a few gotchas when calling an external stylesheet.

Example of Calling External Stylesheet in Sinatra

Let's assume that we have a stylesheet called styles.css. The best practice is to utilize the URL helper in the head tag of the ERB view template file, such as here:

Now that we have this external call, where do we put the file? You might think that you would put it at the root of the application, since that is where it appears that Sinatra is looking for it. However, you'll actually need to create a new directory at the root of the application called 'public'. Add the stylesheet to the public directory and everything will work.

Below is a sample application that has the full application structure.