53

im working on node.js(express) with ejs and im not able to include a .css file to it.i tried the same thing seperately as a html-css duo and it worked fine...how can i include the same in my .ejs file. My app.js goes thus:

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'] 
  });
});

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

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

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


app.listen(3000);

and 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 as to which templating language you use. Templating languages can be a hot topic of debate.Here Iam going to use Jade.</p>
<p class ='just'>Again Express is agnostic to what you use to generate your CSS-you can use vanilla CSS but for this example I'm using Stylus.
</p>
<footer>
Running on node with express and ejs
</footer>
</home>
</html>

style.css file:

<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>
1
  • 1
    You shouldn't use the style tags in your css file and you might need to create routes with express that serve your css and other assets. Commented Sep 5, 2013 at 7:06

7 Answers 7

186

Your problem is not actually specific to ejs.

2 things to note here

  1. style.css is an external css file. So you dont need style tags inside that file. It should only contain the css.

  2. In your express app, you have to mention the public directory from which you are serving the static files. Like css/js/image

it can be done by

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

assuming you put the css files in public folder from in your app root. now you have to refer to the css files in your tamplate files, like

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

Here i assume you have put the css file in css folder inside your public folder.

So folder structure would be

.
./app.js
./public
    /css
        /style.css
Sign up to request clarification or add additional context in comments.

Comments

18

In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:

  1. Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"

  2. In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… /> as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head> section

    <link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
    
  3. In your server.js file, you need to use the app.use() middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use() middleware there is already a function/method provided by express called express.static(). Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:

    // using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
    // app.use("/route", express.static("foldername"));
    app.use('/public', express.static('public'));
    

After following these simple 3 steps, every time you res.render('ejsfile') in your app.get() methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.

Comments

14

You can use this

     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
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

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

I try this for some custom css. It works for me

Comments

5

As I see you are using EJS with express.js

  • Firstly, there is a better way to add EJS

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

    and for that, your file structure should be like

     .
     ./app.js
     ./view
         /index.ejs
    
  • And for adding CSS to your EJS file, you have to use "public" folder (or any other name, name doesn't matter) from which you can serve static file like CSS, JS or images

    For accessing that, you can use

     app.use(express.static("public"));  //better and newer way than first answer
    

    and is your EJS file, you can link your CSS by

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

    Here I am assuming that, you put your CSS file in your CSS folder inside public folder

    So, your file structure will be like

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

Comments

4

I tried a different approach. I created an ejs file for my styles called styles.ejs and added all the css inside the tags like this.

<style>
    body {
      font-family: Tahoma, Geneva, Verdana, sans-serif;
    }

    #container {
      margin: 0 10%;
      padding: 20px;
      border: 10px solid #c8102e;
    }
</style>

and I have includes this file inside head tag of my index.ejs like this.

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

It worked well for me.

Comments

0

Add below code to serve static files

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

create a folder named public in your root folder and add your styles files inside public folder.and change your linking css code as below.

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

So folder structure should be:

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

1 Comment

Why are you mixing HTML with your JavaScript? You should clarify that those two lines of code should be in different files.
0

If you still looking for a solution try this:

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

You have to configure the path correctly in your app.js or index.js file so it can render the file from the correct location.

const express = require("express");
const app = express();
const router = require("./routers/router");
const path = require("path");
app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, "public")));

app.use("/", router);

app.listen(3035, (req, res) => {
  console.log("listening on port 3035");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.