Ways to connect css file to ejs views in nodejs

Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates.

In an effort to address this issue, I created a public directory to store assets such as images and external CSS files. Subsequently, I attempted to link the static contents to Express using:

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

While the images (.jpg) stored in my public folder are being rendered correctly, the CSS file within that same directory is not displaying properly.

File Structure: 
node_modules
models
views
public > app.css, hero.jpg
server.js
package.json

Below is a snippet of my Express app configuration from server.js:

const express = require('express');
const app = express();
const ejs = require('ejs');
app.use('/public', express.static(__dirname + '/public');
app.set("view engine", "ejs");
app.set('views',__dirname+'/views');
app.get('/', (req,res) =>{
   res.render('home',{
        title: "HomePage",
        date : new Date().getFullYear()
        });
});
app.listen(3000);

Within the home.ejs file, the head section includes:

<head>
<meta charset = "utf-8">
<title> My Website <%= title %> </title>
<link rel="stylesheet" href="/app.css" type="text/stylesheet">
</head>

Despite my expectations for the app.css file to load successfully based on the code above, it seems that it's not functioning as intended within the home.ejs file.

Answer №1

From looking at your code, it seems like you've defined the static file folder as /public.

To make sure your CSS link is correct, try changing it to

<link rel="stylesheet" href="/public/app.css" type="text/stylesheet">

Alternatively, you can set the static file configuration like this:

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

Then, update your CSS link to

<link rel="stylesheet" href="/static/app.css" type="text/stylesheet">

Answer №2

To declare your public folder correctly, use the following method:

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

This will allow you to serve files as if they were in the root folder. You can then link your CSS and images like this:

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


// for an image
<img src="/hero.jpg">


If you declare the public folder like this:

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

You are setting a virtual path prefix for your files. In this case, you need to add public in the URL path of each file, such as

<link rel="stylesheet" href="/public/app.css" type="text/stylesheet">

Answer №3

If you want to specify the absolute path of the directory to be used as part of the public folder:

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

First, create a public folder within the root directory. Inside this folder, you can create a css folder if needed. This will give you a structure like public/css/style.css

To access the style.css file, simply use:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to iterate through an array and reverse its order

Is there a way to loop through an array and change the CSS background color chronologically rather than randomly? Additionally, is it possible to reverse through the same array when the back button is clicked? http://jsfiddle.net/qK2Dk/ $('#right&a ...

What is the best way to seamlessly transition from responsive design to mobile design?

While developing a single-page app, I encountered an issue with the layout when the screen width reaches a specific point. On narrow screens, I prefer to utilize the full width, but for wider screens, I want to limit the width for better readability. The l ...

I have a few inquiries about my nodejs studies. Can you assist me, please?

As I delve into my studies of nodejs, some burning questions have arisen. Is it true that nodejs supports all JavaScript? In the official documentation, it mentions using the latest v8 engine. However, I have reservations about whether all JavaScript ...

Ensure that the responsive SVG image remains centered even when resizing

I have been attempting to center crop the responsive SVG image while resizing. Even though I used preserveAspectRatio="xMidYMax slice", the image width does not stay consistent with my screen size. body{ margin:0;padding:0; } .wrapper { position: re ...

Querying specific documents with Angular Firebase reference is a breeze

I'm currently encountering an issue when attempting to query documents in one collection with a reference to another document in a separate collection. Here is the scenario I am dealing with: There are two collections: "posts" and "users". Every "pos ...

Tips for eliminating unwanted white space underneath your webpage while zooming on a mobile device

Currently developing a responsive website, everything is running smoothly except for one issue. When I pinch zoom in on mobile and scroll down, a large white bar appears below the entire page, stretching across the screen width. How can this be fixed? Belo ...

Unable to pre-commit: encountered an unforeseen error while trying to spawn UNKNOWN in the Jhipster project

Encountered an issue during the commit process! node : v16.16.0 generator-jhipster : 6.10.1 Error message: $ git commit -m "message" husky > pre-commit (node v16.16.0) Stashing changes... [started] Stashing changes... [skipped] → No partia ...

Scan across a lineup of pictures

I am looking to showcase a series of images in a horizontal alignment, but I want to avoid overloading the screen width. My goal is to allow users to navigate through the images using their mouse - when they move right within the image container, I want t ...

Issues with Gulp and Browser Sync integration

Encountering errors while running Gulp with Browser Sync in Chrome: NonESPMessageInterface --- nonEspMessageInterface.js:8 TypeError: Cannot read property 'insertBefore' of null --- angular.js:13708 Checklist message was invalid, from origin # ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

What is the best way to choose all <pre> tags that have just one line of content?

$('pre:contains("\n")') will target all <pre> elements that have one or more newlines. Is there a way to specifically select <pre> tags with no newline or only one at the end? Any shortcuts available? match <pre>A< ...

The latest update to the Server Stats code mistakenly changes the channel to "undefined" instead of displaying the total number

I've been working on a private bot for a specific server that displays server statistics and more. However, I've encountered an issue where every time a user joins or leaves the guild, the bot updates a channel with 'undefined' instead ...

Enhancing Bootstrap Slider Range with jQuery/Javascript

Currently, I have incorporated the Bootstrap slider into a webpage that features two sliders on a single page. The range of the second slider depends on the value of the first one. It is crucial for me to be able to update the range of the second slider af ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

Counting duplicate values associated with the same key in a JSON array using JavaScript/NodeJS

Hello everyone, I could really use some assistance in solving this issue. If this has already been asked before, please direct me to the original question. Currently, I am working with a JSON array of elements. For example: var data = [{"key":"Item1"},{ ...

Adjusting the size of the BrowserWindow in Electron

Is there a way to adjust the size of the BrowserWindow during runtime instead of just at startup? I have come across solutions that involve initializing the window with specific width and height values like this: var win = new BrowserWindow({ width: 800, ...

Error in Node JS: When attempting to use "require", a ReferenceError is thrown

After deciding to utilize a MySQL database, I proceeded by installing MySQL using the command npm i mysql. Following the installation, I included the line of code below in order to begin utilizing it: var mysql = require('mysql'); However, upon ...

Prevent Express.js app from experiencing crashes

The way Express.js handles uncaught exceptions has been quite unpredictable for me. At times, the request will come back with a status code of 500 indicating an internal error but continue to run, while other times it crashes and displays [nodemon] app c ...

Say goodbye to tables and hello to CSS div layouts!

Is there a way to align three or four elements without relying on tables? I want them to follow this format: The reason I am asking is because my current method involves using tables, but they are not allowing me to set a specific height for the "test" bo ...

Transmit precise data through socket.io to the client using socket.send

Is there a way to send and retrieve a specific variable when using socket.send? I need to send arrays of text as separate variables in my project using node.js to communicate data to the client-side (html). I understand that something is not quite right w ...