简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM