How to include CSS files in EJS View Engine?
Last Updated :
28 Feb, 2024
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.
Approach to include CSS file in EJS:
- We’re building a Node.js web application using Express and EJS.
- Our project includes a basic webpage styled with CSS.
- We’ve set up routes to render EJS templates, ensuring the text content is centered within a styled container.
Steps to Include CSS files in EJS:
Step 1: let’s create a new Node.js project. Open your terminal and run the following commands:
mkdir nodejs-express-ejs
cd nodejs-express-ejs
npm init -y
Step 2: Install dependencies for our project using the following command in the terminal.
- Express is a web application framework for Node.js
- EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.
npm install express ejs
Step 3: After setting up the Node environment on your system, we can start by creating a server.js file and create two directories by the names of Views in which we will write our EJS fil,es and Public in which we will write the CSS files.
Project Structure:
Project Structure
The updated dependencies in the package.json file will look like this.
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}
Example: Here, we will demonstrate how to include CSS files using Node.js, Express, and EJS
Javascript
const express = require( 'express' );
const app = express();
const path = require( 'path' );
app.set( 'view engine' , 'ejs' );
app.use(express.static(path.join(__dirname, 'public' )));
app.get( '/' , (req, res) => {
res.render( 'index' );
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(
`Server is running on
http:
);
});
|
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content=" width = device -width,
initial-scale = 1 .0">
< title >
Node.js Express EJS Example
</ title >
< link rel = "stylesheet"
type = "text/css"
href = "/css/style.css" >
</ head >
< body >
< div class = "container" >
< h1 >
Welcome to Geeks
for Geeks
</ h1 >
< p >
This is a basic example of
including css files to ejs
</ p >
</ div >
</ body >
</ html >
|
CSS
body {
font-family : Arial , sans-serif ;
background-color : #f0f0f0 ;
margin : 0 ;
padding : 0 ;
}
.container {
max-width : 800px ;
margin : 50px auto ;
padding : 20px ;
background-color : #222221 ;
border-radius: 5px ;
box-shadow: 0 0 10px rgba( 0 , 0 , 0 , 0.1 );
text-align : center ;
display : flex;
flex- direction : column;
justify- content : center ;
}
h 1 {
color : #2f8d46 ;
}
p {
color : white ;
}
|
Output:
Including CSS files to EJS
Share your thoughts in the comments
Please Login to comment...