Damian Piotrowski
Damian Piotrowski

Reputation: 13

Can't apply CSS to Views in ASP.NET MVC

I have problem with styles in my ASP.NET MVC app.

That's my head tag in _Layout.cshtml:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>@ViewBag.Title</title>
    <link href="~/lib/bootstrap/css/bootstrap.css" rel="stylesheet" />
    <link href="~/content/site.css" rel="stylesheet" />
</head>

site.css is my CSS file, the problem is that I have a home view (index.cshtml) which has only divs inside. It renders but none of my styles work with it.

But when I type styles locally like:

<div class="middle" style="width:500px; height:200px;">

then they are applied to the div.

Do I need to set styles in every view, or is there way to make views use _Layout styles?

Upvotes: 1

Views: 3674

Answers (2)

Flowra
Flowra

Reputation: 1408

In my case the browser need to refresh the view without cache, I just refreshed the chrome with cntrl + f5 and the style sheet applied

Upvotes: 1

Zhi Lv
Zhi Lv

Reputation: 21353

Based on your code, I assume your application is an Asp.net 5/6 or Asp.net core MVC application, right?

If that is the case, please check the index.cshtml page, whether it specify a layout by setting Layout property. Code like this:

@{
    ViewData["Title"] = "Index";
    Layout = "_Layout";
}

If still not working, open the Views folder, the structure should like this:

enter image description here

The _Layout page is in the Shared folder, and under the Views folder, we should also add the _ViewImports.cshtml page with the following content:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

and add the _ViewStart.cshtml page with the following content:

@{
    Layout = "_Layout";
}

After that, in the MVC view pages, we can use the Layout property to specify the layout page.

Finally, if the style still not working, try to use F12 developer tools to check whether the CSS file is load success, if not check the file path is correct or not. And in the Program.cs file (for Asp.net 6) or the Startup.cs file(Asp.net core 1~3 or Asp.net 5), enable the Static files middleware. Code like this:

app.UseStaticFiles();

You can check this screenshot: this is an Asp.net 6 MVC application.

enter image description here

More detail information about layout, see Layout in ASP.NET Core

Upvotes: 2

Related Questions