thompsonrapier
thompsonrapier

Reputation: 175

How do I call an external stylesheet from a .cshtml page?

I have a view page (View.cshtml) and a stylesheet (Style.css).

The stylesheet is located in a folder called "Stylesheet", and the view page is located in Views/Home/View.cshtml. I am trying to link the stylesheet to the view page by this code:

<link rel="stylesheet" type="text/css" href="~/Stylesheet/Style.css">

When I run the project, it showed the contents of the view page but the styling was not implemented. May I know what I am doing wrong?

UPDATE:

View.cshtml

<!DOCTYPE html>

<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="~/Stylesheet/Style.css" /> ‌
    <title>Test Page</title>
</head>

<body>

    <div id="topHeader">
        <br />

        <div id="credentialsBox">

            <div id="texts">
                <div id="word1">Username:</div>
                <div id="word2">Password:</div>
            </div>
        </div>
    </div>
</body>

Style.css

@font-face {
    font-family: 'proximanova';
    src: url('../fonts/proximanova-light-webfont (2)_0.ttf') format('truetype');
}


/*CSS Styling Properties*/
body {
    font-family: proximanova;
    margin: 0;
    background-color: #007381;
}

#topHeader{
    margin-top: 15%;
    height: 450px;
    background-color: #d6d6d6;
}

#credentialsBox {
    border-radius: 3%;
    width: 20%;
    margin: auto;
    margin-top: -5%;
    background-color: #ffffff;
}

#texts {
    padding: 14%;
    text-align: center;
}

_Layout.cshtml

<!DOCTYPE html>
<html>

    <head>
        @RenderSection("css", false)
    </head>

    <body>
        @RenderBody()
    </body>

</html>

Sorry if the CSS styling is a bit messy, I am trying my best to learn here :D

Upvotes: 1

Views: 5147

Answers (3)

thompsonrapier
thompsonrapier

Reputation: 175

I have solved the error. I placed my stylesheet inside "wwwroot/css" and it worked.

Upvotes: -1

PhatLee
PhatLee

Reputation: 37

If you that is your own custom CSS file then make sure that you add that file to BundleConfig.cs file in App_Start folder. Which will look something like this..

  bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/site.css",
                  "~/Content/Style.css));

And in your head section try to replace

<head>
    @RenderSection("css", false)
</head>

with

  <head>
  @Styles.Render("~/Content/css")
  </head>

and see it will make any difference, and we will go from there.

Upvotes: 0

Shaiju T
Shaiju T

Reputation: 6607

You can also use @Url.Content instead for absolute path of css file.

<link href="~/Stylesheet/Style.css" rel="stylesheet" type="text/css" />

or

<link href="@Url.Content("~/Stylesheet/Style.css")" rel="stylesheet" type="text/css" />

Upvotes: 2

Related Questions