Currently I'm trying to use a partial view inside one of my views which uses a different css style sheet. However, the styles from the main view are being carried over because of the way styles are rendered in Razor: @Styles.Render("~/Content/css")
simply applies to everything, and I can't seem to find any documentation on scoped css in Razor.
Doing the below code does not work - I believe because Razor handles Styles.Render by simply placing in the head.
<div>
<style scoped>
@Styles.Render("~/Content/othercss")
</style>
@Html.Partial("~\\Views\\Layouts\\blog.cshtml")
</div>
Does anyone know of a workaround for this?
Styles.Render()
renders link tags for the browser to grab the CSS file, something like this:
<link rel="stylesheet" type="text/css" href="https://whatever.css">
Which is not what is expected to be inside a style
element. What you want to do it output the content of that CSS file, for example:
<style scoped>
@Html.Raw(File.ReadAllText(Server.MapPath("~/Content/yourfile.css")))
</style>
Note that this isn't using your bundle, to do that you would need to access the bundle and render that somehow (outside of the scope of this answer).
Having said all this, note that the docs for the scoped
attribute say this:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behaviour my change in the future.
Obsolete
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
A better option would be to scope your CSS in the first place. For example:
div#wrapper .red {
background-color: red;
}
And now this style will only apply inside a div
with id of wrapper
. Ans if you're writing your CSS in something like SASS (which you really should be!), it's even easier:
div#wrapper {
.red {
background-color: red;
}
.some-other-style {
display: block
}
}