Including a .css file in ejs

I'm currently developing an application using Node.js (express) with EJS, and I'm facing an issue while including a .css file in it. When I tried the same setup as a standalone HTML-CSS project, it worked perfectly fine. How can I include the CSS file in my .ejs file? Here is how my app.js looks:


var express = require('express');
var app = express();

app.set('views', __dirname + '/views');

app.get('/', function(req, res){
  res.render('index.ejs', {
        title: 'My Site',
    nav: ['Home','About','Contact'] 
  });
});

// more routes...

app.listen(3000);

And here is the content of the index.ejs file:

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

<body>
<div>
    <h1> <%= title %> </h1>
    <ul>
    <% for (var i=0; i<nav.length;i++) {%>
        <li><a href="/<%=nav[i]%>"> <%=nav[i]%> </a></li>
    &nbsp;  
    <% } %>
    </ul>
</div>

<br>
<h3>Node.js</h3>
<p class='just'>Express is agnostic to which templating language you use. The choice of templating language can be subjective.</p>
<p class ='just'>It's also worth noting that Express doesn't enforce any specific CSS preprocessor. For this example, Stylus is utilized.</p>
<footer>
Running on node with express and ejs
</footer>
</home>
</html>

The style.css file content:

<style type="text/css">
body { background-color: #D8D8D8;color: #444;}
h1 {font-weight: bold;text-align: center;}
header { padding: 50px 10px; color: #fff; font-size :15px; text-align:right;}
 p { margin-bottom :20px;  margin-left: 20px;}
 footer {text-decoration: overline; margin-top: 300px}
 div { width:100%; background:#99CC00;position:static; top:0;left:0;}
 .just
 {
    text-align: center; 

 }
a:link {color:#FF0000;}    /* unvisited link */
a:visited {color:#0B614B;} /* visited link */
a:hover {color:#B4045F;}   /* mouse over link */
a:active {color:#0000FF;}

  ul { list-style-type:none; margin:0; padding:0;text-align: right; }
li { display:inline; }
</style>

Answer №1

Your issue is not specific to ejs, it applies to general web development practices.

There are two important points to consider:

  1. style.css should be an external css file and thus does not require style tags within the file. The file should only contain the css styles.

  2. In your express application, ensure that you specify the public directory from which static files such as css, js, and images are served.

This can be achieved by adding the following line in your app:

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

Assuming you have placed your css files within the public folder of your app root, you need to reference them correctly in your template files, for example:

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

In this scenario, it is assumed that the css file is located within the css folder inside the public directory.

The folder structure would look like this:

.
./app.js
./public
    /css
        /style.css

Answer №2

If you want to add a static CSS file to your express app (for styling ejs "templates" files), here are the straightforward 3 steps you need to follow:

  1. First, place your CSS file named "styles.css" in an "assets" folder within a "public" folder. The relative path to the CSS file should be "/public/assets/styles.css"

  2. In each of your ejs files, include the CSS file by linking it in the <head> section using

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

  3. In your server.js file, use the app.use() middleware with express.static() to serve up static CSS files. Also, specify a request route that will respond to and serve up the files from the public folder every time the middleware is called.

After completing these 3 steps, whenever you use res.render('ejsfile') in your app.get() methods, the CSS styling will automatically be applied. Test this by accessing your routes in the browser.

Answer №3

If you want to include custom CSS in your site, you can follow these steps:

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

To apply the custom CSS from the template, use the following code:

   <%- myCss.style %>

Create a file named style.css with the following content:

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

This method worked well for me when I needed to add some custom styling to my project.

Answer №4

It seems like you're utilizing EJS with express.js

  • There's a more efficient method for incorporating EJS

     app.set("view engine", "ejs");
    

    and in order to do so, your file structure should resemble this:

     .
     ./app.js
     ./view
         /index.ejs
    
  • To add CSS to your EJS file, it's necessary to utilize the "public" folder (or any alternative name)

    In order to access that, you can implement the following:

     app.use(express.static("public"));  //a better and newer approach than the initial solution
    

    Within your EJS file, you can connect your CSS by using:

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

    This assumes that your CSS file is located within the CSS folder inside the public directory

    Therefore, your file structure will be as follows:

     .
     ./app.js
     ./public
         /css
             /style.css
     ./view
         /index.ejs
    

Answer №5

Instead of the traditional method, I decided to take a new approach. I set up an ejs file named styles.ejs specifically for my styles and placed all the CSS code within appropriate tags.

<style>
    body {
      font-family: Arial, Helvetica, sans-serif;
    }

    #wrapper {
      margin: 0 auto;
      padding: 15px;
      border: 5px solid #f44336;
    }
</style>

After that, I included this file in the head section of my index.ejs document like so:

<head>
   <%- include('./css/styles'); %>
</head>

This approach proved to be successful for my project.

Answer №6

To include static files, you can use the following code snippet:

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

Create a directory named public in the root folder of your project and place all your style files inside this public folder. Update your CSS link code as shown below.

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

Your folder structure should look like this:

.
./app.js
./public
   /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

Strategies for limiting a table row in JavaScript or jQuery without utilizing the style tag or class attribute for that specific row

I am looking for a way to limit the display of records in a table. Currently, I can restrict the table rows using the style property, but this causes UI issues such as missing mouse-over effects for the entire row. I need to ensure that mouse-over functi ...

CSS Only flyout navigation - reveal/hide with a tap or click

I want to make adjustments to a CSS-only menu that has a horizontal flyout effect triggered by hovering. I am looking to achieve the same effect on touch or tap - meaning, one tap to open the menu and another tap to close it. Is it possible to accomplish ...

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

Changing buffer from base64 to UTF-8 encoding in Node.js

My application imports messages from the Notes folder of Gmail using the imap npm module. When following the example on their GitHub page, all message contents are read into a buffer: stream.on('data', function(chunk) { count += chunk.len ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Trying to reduce the cursor box area within an A link containing a div box

My communication skills are lacking, so I have included an image to better illustrate my issue. Here is the problem .body { text-align: center; display: flex; flex-direction: column; align-items: center; } .flex-container { display: flex; ...

Documentation for the API endpoint is not currently visible through the utilization of Swagger and Express

I'm working on documenting my API with Swagger. I've managed to integrate Swagger into my express project successfully, but I'm facing an issue where the documentation for endpoints doesn't show up when they are in a route file separate ...

Is it possible for API calls and database queries to create a bottleneck? Exploring the impact of Node.js and

Our frontend is built with React and the backend utilizes Node.js. At the moment, we are storing carts for unregistered users in MongoDB using sessions (with express-session and connect-mongo). In our frontend, I am currently making an API call every tim ...

Tips for correctly displaying partial views and incorporating JavaScript files via AJAX in Express/Jade?

Explanation In my current web application, I am utilizing Express along with Jade. I'm encountering challenges when it comes to rendering partial views for AJAX navigation purposes. Although I have two distinct questions, they are intertwined, so I& ...

How can you make the coordinates of the cursor track the cursor when it hovers over a rectangle?

The code provided below will constantly display the cursor's coordinates right below the cursor: function displayCursorCoordinates(e) { var x = event.clientX; var y = event.clientY; var coordinates = "(" + x + ", " + y + ")"; document.getEl ...

Failed to access the 'totalQty' property as it is undefined

I have developed a cart object that can hold products in a shopping cart. The issue arises when an item is undefined before it gets added to the cart. How can I ensure that the cart is defined even when it's empty during the session? I am using ejs. ...

Error loading module - Firebase Cloud Functions module not found

Currently, I am in the process of developing a Node.js function that will be deployed within Firebase Cloud Functions. This particular function requires the use of faker.js to aid in generating mock testing data. Unfortunately, an issue arose while trying ...

css code creates a stable block with a blurred transparent effect

I need assistance with creating a transparent fixed header using only CSS and no JS. I attempted to use ::before for creating a blur effect with a negative z-index, but so far, my attempts have failed. I know how to achieve this using jQuery, but I am spec ...

Transitioning between sections by clicking on a navigation menu item

I'm looking to create a cool animation effect on my website. When a user clicks on a specific menu link, such as "about-section," I want the page to smoothly scroll down to that section in a parallax style. If anyone knows of a jQuery plugin that cou ...

Adjusting the size of icons to fit within a container

I need a div that can display up to 7 icons, depending on certain selections. These icons are from ionicons library. Here is the current code snippet: <div class="item item-text-wrap" style="text-align:center;"> <button class="button" style=" ...

Error message: "Maximum width header anomaly"

I've been working on a full-width header tumblr theme and everything looks great until I resize the screen to a smaller size, like on a mobile or tablet. The header ends up cutting off and no longer maintains its full width. You can see an example of ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Upon installation, swagger may generate a notification about a dependency concern

My attempt to install Swagger via npm using this link is being met with a warning message as shown below- npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31424650565654431c1c5e585555">[email protected]</a> ...

Browsing through the last items on a webpage

I have set up a jsfiddle that explains itself quite well: http://jsfiddle.net/nt7xzxur/ with the following smooth scrolling code: function smoothScroll(hash) { $('html, body').animate({ scrollTop: $(hash).offset().top }, 750); By clicking o ...

Node Express JS: Efficiently handling multiple fetch responses before sending data to client

My goal is to call an API that only accepts one animal name at a time, but I receive the names of multiple animals in a query separated by commas. To achieve this, I plan to call the API once for each animal, push the JSON data into an array, and then resp ...