I'm using Sinatra, and I've been trying to load in some stylesheets. I've tried just the normal html link
tag in my erb, but that hasn't worked.
ive tried
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
It's not an issue with the url i'm using, is there some special way of achieving this?
You can't. The last stylesheet you specify will be the one html page will use. Think of it as a big single .
For example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head> .
you can create a new CSS file and centralize all with @import feature, then just use the new CSS in your site. Use webpack to bundle all your CSS files into one file. Then `<link>` it into the web page. well i just add them as external css links, givng them a proper names.
Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword.
When you use href="style.css"
, you’re specifying a relative link to the stylesheet. The actual path that your browser will request will depend on the url of the current page, so for example if you have a route like:
get '/things/:id' do
#look up thing with id = :id
erb :my_view
end
then the browser will look for the stylesheet at /things/style.css
. This obviously won’t work if your stylesheet is at the top level in your public
dir.
The quick fix is to use an absolute path to your stylesheet: href="/style.css"
(note the /
character). This will make the browser always look for the stylesheet at the root of the server.
This assumes that your application is always mounted at the root of your server, and will fail if your run it in a subdirectory. You want to be able to say “look for the stylesheet in the root of this application, wherever it happens to be”. In Sinatra you can do this by using the url
helper method. Using ERB as your template language this would look like:
<link href="<%= url('/style.css') %>" rel="stylesheet" type="text/css" />
This will ensure the link to style.css
will be correct wherever your app is located.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With