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

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


in app.js:

 you must first declare static directory app.use("/styles",express.static(__dirname + "/styles"));

in ejs file :

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


Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,

const app = express();const publicDirectoryPath = path.join(__dirname, '../src/public');const staticDirectory =  express.static(publicDirectoryPath);app.use(staticDirectory);

and my folder structure was like

enter image description here

The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.

Above example was for only one static path. For multiple static path you can use the code in the below

const app = express();const publicDirectoryPath = path.join(__dirname, '../src/public');const cssDirectoryPath = path.join(__dirname, '../src/css');const staticDirectory =  express.static(publicDirectoryPath);const cssDirectory =  express.static(cssDirectoryPath);app.use(staticDirectory);app.use('/css/',cssDirectory);

And my generic HTML file is

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Index</title>    <link rel="stylesheet"  href="../css/styles.css"></head><body><h1>this is index page</h1></body></html>