Adding .CSS File to Ejs

adding .css file to ejs

Your problem is not actually specific to ejs.

2 things to note here

  1. style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.

  2. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image

it can be done by

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

assuming you put the css files in public folder from in your app root.
now you have to refer to the css files in your tamplate files,
like

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

Here i assume you have put the css file in css folder inside your public folder.

So folder structure would be

.
./app.js
./public
/css
/style.css

Adding CSS to EJS

You specified that the static files (css, images, etc) are on the folder "public" :

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

Read : http://expressjs.com/en/starter/static-files.html

Just move your css on this folder ;)

edit :

You can specify multiple static folder :

app.use("/public1", express.static(__dirname + "/public1"));
app.use("/public2", express.static(__dirname + "/public2"));

But you can add folders in your static folder :

  • /public1/css
  • /public1/lib

and use it like that in your ejs file :

<link rel="stylesheet" href="/public1/css/index.css">

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

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" />

Adding CSS File to ejs tempelate using variable from server side

Method to include :

<% var css_link = '/stylesheets/' + cssa + '.css'; %>
<link rel="stylesheet" type="text/css" href="<%= css_link %>" >

Credit goes to @SpiRT

Alternatively :

<link rel="stylesheet" type="text/css" href="/stylesheets/<%=cssa%>.css">

Can't get stylesheet to work with ejs for node.js

Declare a static directory:

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

<link rel='stylesheet' href='/style.css' />

Not link css file with ejs

You have a wrong setup, Your view folder should only contain view files (in your case *.ejs files) but not static content.
Create another folder with name 'public' at root of your node project and move your main.css there and add the following code to serve static content.

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

After this you should be able to access your main.css using localhost:5000/main.css If you see your content, The css import in your view file will start working.



Related Topics



Leave a reply



Submit