How to include css files using NodeJS, Express, and EJS?
Last Updated :
28 Feb, 2024
CSS stands for “Cascading Style Sheet”. It is used to style web pages. CSS simplifies the process of making web pages presentable. It describes how web pages should look it prescribes colors, fonts, spacing, and much more. Including CSS files is important for styling web pages in web development with Node JS, Express, and EJS. In this article, we will explore the process of including CSS in such projects to enhance the visual appeal and user experience.
Steps to include CSS files using NodeJS, ExpressJS, and EJS:
Step 1: let’s create a new NodeJS project. Open your terminal and run the following commands:
npm init -y
Step 2: Install the necessary package in your file using the following command.
npm install express ejs
Project Structure:
Project Structure
The updated dependencies in the package.json file will look like this.
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1"
}
Here, we will demonstrate how to include CSS files using Node.js, Express, and EJS
Javascript
const express = require( 'express' );
const path = require( 'path' );
const app = express();
app.use(express.static(path.join(__dirname, 'public' )));
app.set( 'view engine' , 'ejs' );
app.set( 'views' , path.join(__dirname, 'views' ));
app.get( '/' , (req, res) => {
res.render( 'index' );
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >My Website</ title >
< link rel = "stylesheet" href = "/styles/main.css" >
</ head >
< body >
< h1 >Welcome to My Website</ h1 >
< p >This is a sample paragraph.</ p >
</ body >
</ html >
|
CSS
body {
font-family : Arial , sans-serif ;
background-color : #f0f0f0 ;
}
h 1 {
color : #b00a0a ;
}
p {
color : #7051e9 ;
}
|
Start your application using the following command.
node server.js
Output:
CSS applied to EJS
Share your thoughts in the comments
Please Login to comment...