WillemvanderVeen WillemvanderVeen - 3 years ago 237
Node.js Question

Adding CSS to EJS

Have difficulties linking my css files when using EJS.
Already looked into other answer but can't figure it out
This is the code I used reference for my css file.

EJS



<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>
<header>
<% include header %>
</header>
</body>
</html>


The css file is in the same directory as the ejs files, the views directory. Can this cause any problems? The header is just another ejs file with some static html.

server:



const express = require("express");
const path = require('path');
const app = express();

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");


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

app.get('/', (req, res) => {
res.render("index");
})

app.listen(3000);


I Eventually want to move my css files in another folder but I was really wondering why this doens't work. Since the files are in the same folder I expected the relative path
<link rel="stylesheet" href="index.css">
to work.

Answer Source

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">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download