1

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.

2 Answers 2

5

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">
Sign up to request clarification or add additional context in comments.

Comments

1

The reason it doesn't work is simply because the folder containing your .ejs files is not actually being served. When rendering a view, express will locate your .ejs file locally on the server and read its contents, but it will not make it available over a HTTP connection.

You can verify this by trying to access the .ejs file directly via your browser.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.