Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placement of style tag in view

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 image 406
Jonathan Wood Avatar asked Sep 05 '25 02:09

Jonathan Wood


2 Answers

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>
}
like image 142
Serj Sagan Avatar answered Sep 07 '25 16:09

Serj Sagan


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:

  • pauses rendering
  • reconstructs CSSOM to include the new declarations
  • rebuilds the already rendered DOM (this is where FOUC happens, if)
  • carries on with rendering
like image 30
tao Avatar answered Sep 07 '25 18:09

tao