Looking at some Razor views, I see a lot of times where a <style>
tag is added directly in a view (CSHTML) file.
This seems to work fine, but in fact it adds the <style>
tag inside the <body>
tag, while it should generally be inside the <head>
tag.
How would you some inline CSS to a single razor page so that it appears within the <head>
tag? Is there a preferred way?
Like this:
Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
...
@RenderSection("HeadStyles", required: false)
</head>
<body>
...
</body>
</html>
Home/Index.cshtml
or whatever other view you need to do this in
@section HeadStyles {
<style>
.custom-style { color: red; }
</style>
}
The reason why inclusion of <style>
tags is not recommended inside <body>
is because of causing FOUC.
But if your <style>
tag applies to content that's after it in DOM, that risk is null
.
No browser currently in use has any trouble parsing <style>
tags placed in <body>
.
Technically, when the browser meets a <style>
tag in DOM it:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With