ASP.NET Core 8 Website - CSS and Static Files
PART 4: Adding CSS and Static Files
This part gives the Home, Privacy and 404 pages a consistent appearance by serving a stylesheet from ASP.NET Core's static-file directory.
1. Create the CSS directory
mkdir -p wwwroot/css
On Windows Command Prompt:
mkdir wwwroot
mkdir wwwroot\css
2. Create wwwroot/css/site.css
* { box-sizing: border-box; }
html {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
}
body {
margin: 0;
color: #212529;
background-color: #ffffff;
}
.site-header {
background-color: #ffffff;
border-bottom: 1px solid #dee2e6;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.navigation {
display: flex;
align-items: center;
max-width: 960px;
min-height: 56px;
margin: 0 auto;
padding: 0 16px;
}
.site-name {
margin-right: 24px;
color: #212529;
font-size: 20px;
text-decoration: none;
}
.nav-link {
margin-right: 18px;
color: #212529;
text-decoration: none;
}
.site-name:hover, .nav-link:hover { color: #0d6efd; }
.page-content {
max-width: 960px;
margin: 0 auto;
padding: 24px 16px;
}
.home-content { text-align: center; }
.home-content h1 { margin: 0 0 8px; font-size: 40px; font-weight: 400; }
.home-content p { margin: 12px 0; }
.error-code { color: #b02a37; }
@media (max-width: 600px) {
.navigation { flex-wrap: wrap; padding-top: 12px; padding-bottom: 12px; }
.site-name { width: 100%; margin-bottom: 10px; }
.home-content h1 { font-size: 32px; }
}
3. Enable static files
Add this immediately after builder.Build():
var app = builder.Build();
app.UseStaticFiles();
4. Link the stylesheet
Add this inside the <head> of all three HTML responses:
<link rel="stylesheet" href="/css/site.css">
5. Add classes to the markup
<header class="site-header">
<nav class="navigation">
<a class="site-name" href="/">basicdotnet</a>
<a class="nav-link" href="/">Home</a>
<a class="nav-link" href="/privacy">Privacy</a>
</nav>
</header>
On Home, use <main class="page-content home-content">. On Privacy and 404, use <main class="page-content">. Give the 404 heading class="error-code".
6. Test the site
dotnet run
Test /, /privacy, and an unknown route. You can also open /css/site.css directly to confirm that ASP.NET Core is serving the file.
The row containing basicdotnet, Home and Privacy is the navigation area. Its white background makes it subtle; the bottom border and shadow define its boundary.
Current limitation
Program.cs still contains three copies of the document structure, head section, navigation markup and stylesheet link.
Next: PART 5 converts the manually generated endpoints into Razor Pages.