Andywhatsoever45
Andywhatsoever45

Reputation: 21

CSS Not Loading in Express EJS Project Despite Correct Setup

I'm working on an Express project with EJS templates, and I'm having trouble getting my CSS file to load correctly. I've tried multiple solutions, but the CSS still isn’t applying. Here are the details of my setup:

ejs_portfolio/
├── public/
│   ├── stylesheets/
│   │   └── style.css
│   ├── images/
│   │   └── kawsNWF.png
│   │   └── Potter.png
│   │   └── image1.1.png
│   └── videos/
│       └── Video.mp4
├── views/
│   ├── layout.ejs
│   ├── header.ejs
│   ├── footer.ejs
│   ├── home.ejs
│   ├── aboutMe.ejs
│   ├── contactMe.ejs
│   └── myProjects.ejs
├── routes/
└── app.js

I have express.static set up to serve static files from the public directory.

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

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Routes
const indexRouter = require('./routes/index');
app.use('/', indexRouter);

I’m including style.css in my layout.ejs like this:

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

Steps I've Tried:

  1. Direct Access: I can access http://localhost:3000/stylesheets/style.css directly in the browser, and it shows the raw CSS content, so the file is being served.

  2. Inline Style Test: When I add an inline <style> tag directly in layout.ejs, the styles don't apply. Only HTML inline style works.

    <span style="color: red;">Hello</span>;
    
  3. Network Tab in Developer Tools: When I check the Network tab, style.css shows a 200 status, but none of the styles from this file are applying to the page.

  4. Cache Clearing: I tried clearing the cache and using Disable Cache in Chrome’s Developer Tools with no change.

  5. Minimal Test File: I created a test.html file in public/ with a simple inline <style>, and that worked fine.

Questions:

  1. Are there any other reasons why style.css wouldn’t apply in my EJS layout even though it’s served correctly?

  2. Is there a configuration issue in app.js that I might be missing?

Any help would be greatly appreciated!

Upvotes: 2

Views: 51

Answers (1)

Vishesh
Vishesh

Reputation: 18

The reason might be due to an outdated use of the express.static term. Try using the javascript:

//index.js

import express from "express";

const app = express();
const port = 3000;

app.use(express.static("public"));

and the ejs:

<%# index.ejs %>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="stylesheets/style.css">
</head>

Also, in your terminal, you might need to install express and EJS from npm. Assuming you are using the bash terminal, that would be:

npm init -y

then,

npm i express ejs

This should fix the problem!

Upvotes: 0

Related Questions