Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include css files using node, express, and ejs?

I'm trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can't get my styles.css to load.

From app.js

app.use(express.static(path.join(__dirname, 'public'))); 

In my .ejs, I have tried both of these lines

<link rel="stylesheet" type="text/css" href="/css/style.css" /> <link rel="stylesheet" type="text/css" href="/public/css/style.css" /> 

Neither loads the css. I've gone into the developer's console noticed the type is set to 'text/html' instead of 'text/css'.

My path looks like

. ./app.js ./public     /css         /style.css 
like image 481
stealthysnacks Avatar asked Jul 05 '14 02:07

stealthysnacks


People also ask

How do I embed a CSS file?

CSS can be added to HTML documents in 3 ways: Inline - by using the style attribute inside HTML elements. Internal - by using a <style> element in the <head> section. External - by using a <link> element to link to an external CSS file.

How do you serve HTML and CSS files in node JS?

Code for serving HTML and CSS files in Expressuse(express. static(path. join(__dirname,'CSS')); //This command is used to serve the CSS files which are kept in the CSS folder from the working directory.

How do I read a CSS file in node JS?

To open this, create a public folder inside the main project folder. In it you will find an CSS file under a CSS folder. Uploaded a new CSS file for input field. The folder we just downloaded islocalhost:3000/test/add-username with an original url of http://test.example.com/.


2 Answers

Use this in your server.js file

app.use(express.static(__dirname + '/public')); 

and add css like

<link rel="stylesheet" type="text/css" href="css/style.css" /> 

dont need / before css like

<link rel="stylesheet" type="text/css" href="/css/style.css" /> 
like image 76
Arunkumar Avatar answered Sep 26 '22 15:09

Arunkumar


1.Create a new folder named 'public' if none exists.

2.Create a new folder named 'css' under the newly created 'public' folder

3.create your css file under the public/css path

4.On your html link css i.e <link rel="stylesheet" type="text/css" href="/css/style.css">

// note the href uses a slash(/) before and you do not need to include the 'public'

5.On your app.js include : app.use(express.static('public'));

Boom.It works!!

like image 42
Eric Nderitu Avatar answered Sep 26 '22 15:09

Eric Nderitu