Add CSS with Express js
Add CSS in HTML Page (Inline Method)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home Page</title>
<style>
h1 {
color: orange;
}
a {
text-decoration: none;
padding: 10px 20px;
background: blue;
color: white;
border-radius: 10px;
}
a:hover {
background: rgb(86, 86, 220);
}
</style>
</head>
<body>
<h1>Home Page</h1>
<a href="login">Go to Login Page</a>
</body>
</html>
Is file mein <style>
tag ke andar hi CSS likha gaya hai. Yeh basic styling test karne ke liye kaafi hai.
Make External CSS File
Create a file:
public/css/style.css
style.css
h1 {
color: orange;
}
a {
text-decoration: none;
padding: 10px 20px;
background: blue;
color: white;
border-radius: 10px;
}
a:hover {
background: rgb(86, 86, 220);
}
Add CSS Link in HTML
In home.html
file head section, change:
<link rel="stylesheet" href="css/style.css" />
❌ Don't use:
<link rel="stylesheet" href="public/css/style.css" />
Serve Static Folder in Express
import express from "express";
import path from "path";
const app = express();
const publicPath = path.resolve("public");
app.use(express.static(publicPath));
The express.static()
function allows you to make the files inside the public
folder accessible to the browser.
So when your HTML file includes a line like:
<link rel="stylesheet" href="css/style.css" />
…the browser will be able to find and load that CSS file from the public/css
folder, because you've told Express to serve everything in the public
folder using:
app.use(express.static(publicPath));
Without this, the browser wouldn’t be able to locate the CSS file, even if it's in your project folder. This function tells Express: