How come I am unable to connect my CSS to my EJS files?

Having difficulty linking my css files to my ejs files. Using a standard node.js/express setup, I'm attempting to connect my main.css file from the public/css directory to my index.ejs file in views. The html and routing are functioning correctly. Please see below for the relevant section of my app.js code.

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var contact = require('./routes/contact');
var register_form = require('./routes/register');


var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

In my index.ejs file, the link is placed between the head tags. All filenames have been verified multiple times for accuracy.

 <head>
    <title><%= title %></title>
    <link type="text/css" rel='stylesheet' href='../public/css/main.css' />
  </head>

Answer №1

Within your app.js file, you have properly set the location for your static files by using:

app.use(express.static(path.join(__dirname, 'public')));
. This configuration allows you to easily reference static files like css using absolute pathing starting from the public directory.

To ensure proper linking, update the line of code to:

<link type="text/css" rel='stylesheet' href='/css/main.css' />
and it will function correctly.

It is recommended to stick with this "absolute" pathing method as it ensures that your template pages can be moved around without breaking any css links (for instance, moving

views/index.ejs -> views/pages/index.ejs
).

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

The issue encountered is: npm ERR! Error: EPERM, chmod

I've encountered some issues with npm on my Raspberry Pi while attempting to build a node.js application on a USB device. Here's how my package.json file looks: { "name" : "node-todo", "version" : "1.0.0", "description" : "TodoApp", "ma ...

Resizing background images to their original size using jQuery

Can anyone help me figure out the actual size in pixels of a background image that is being displayed? <style> body { background-image: url(background.jpg); background-size: contain; } </style> I tried using jQuery to get the size of ...

Only store cookies for individuals who have accepted the terms and conditions

In order to adhere to GDPR regulations without using a cookie banner, I want the public pages of my website to refrain from storing cookies. For registered users, I plan to utilize flash messages to enhance their experience. However, incorporating both fea ...

Retrieve a JSON feed from an external streaming source using Node.js

Using Node.js, I've been working with stream-chain and stream-json to stream feeds from both local and remote sources. The code below successfully handles local resources, but how can I modify it to work with external resources as well? Should I downl ...

Ways to modify div content depending on the size of the screen

When the screen size becomes small, my goal is to modify the content within the row divs of the indices_container. Currently, all screen sizes display the index name, price, 1-day change, and year-to-date (YTD) change for each row. I only want to show the ...

Using the ng-show directive in AngularJS allows you to pass elements in

Web Development <li ng-show="sample($event)" TestLi</li> JavaScript Functionality $scope.sample = function($event){ //$event is undefined //perform some action } I have experimented with passing the HTML element using ng-click, but I am curio ...

Trouble with Div Alignment in Web Browsers: Firefox vs. Google Chrome

I have encountered an issue with the layout of my website when using the Div element. While it appears correctly in Internet Explorer, the display gets distorted in Firefox and Google Chrome when the div is expanded. I have searched online for solutions b ...

Navigating Frontend User Permissions in ReactJs and NextJs applications

Currently, I'm developing an application that will cater to various user roles. I am seeking advice on the best way to store permissions for the Frontend in order to dynamically display the appropriate components for each user role. Initially, I att ...

Encountering an error message of "The command syntax is incorrect" after setting up node.js

After updating node.js on my computer yesterday, everything seemed to install correctly. Running the command -v gave me the correct information: node -v This displayed the version number v16.13.1, which is what I was expecting. However, when I tried runn ...

Creating PNG and JPEG image exports in Fabric.js with the help of Node.js

Exploring the wonders of Fabric.JS specifically designed for Node.JS, not intended for web applications, I've successfully created a Static Canvas and added a rectangle to it. Now, it's time to export the image. Take a look at my code snippet bel ...

Anyone able to solve this mysterious CSS alignment problem?

I have a search bar with two image buttons on a webpage I designed using ASP.NET. When I view the page in Internet Explorer 8, Google Chrome or Opera, I noticed that the textbox and image buttons are not aligned properly. The buttons seem to be positioned ...

Trimming content within an editable div in JavaScript: A guide

I am working on an editable div feature where users can input text for comments. My goal is to eliminate any unnecessary spaces before and after the text. For example, if a user types: "&nbsp;&nbsp;Hello&nbsp;world&nbsp;&nbsp;&nbsp ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

What could be the reason for loopback generating the error message: The `ModelDefinition` object is not considered valid?

Currently experimenting with Strongloop. Going through the "Getting Started" tutorials to understand the basic functionalities. Using Windows and PostgresSQL, I set up a new datasource and made changes to the model-config.json to switch the default models ...

Is there a way to enable scroll on v-col?

I'm working on a layout that has specific requirements: The grey container should cover the entire viewport without exceeding it The green v-row should occupy the grey container entirely v-col 1 should utilize all available space and add a scrollbar ...

Having trouble with margin auto 0 not functioning properly in Safari on iPad?

I'm facing a challenge with centering a div in Safari on iPad. It works fine in Chrome, but in Safari there are margins on the left and right which require scrolling to view the whole content. Any suggestions on how to make this work seamlessly in bot ...

Background cutting off right side of HTML website

While updating my supervisor's university website, I noticed a problem with the responsiveness. When resizing the browser window, a horizontal scroll bar would appear and the right side of the website would get covered by the background. On mobile dev ...

Tips for updating information when a button is chosen

Hello everyone, I need some help with a form that has three select buttons. The button labeled "Distribute" is already selected when the page loads, and it contains information about full name, password, and location. How can I use JavaScript to create a c ...

How to handle CSS line wraps: enlarge the second line or determine the number of words per line specifically?

Is it possible to use CSS to control line wraps? I would like to have lines with a similar amount of words per line, or at least avoid one-word lines. Original: A few words for a very long title that will probably span two lines Desired Outcome: A few ...

Is there a method to configure Express to access content from two different file system directories and serve it as one web directory?

Imagine needing a virtual directory on your website that appears as http://whatever/images/, but in reality pulls images from both /Users/me/www/images and /Users/me/moreimages/ on the file system. So when requesting http://whatever/images/selfie.jpg, it s ...