Placement of style tag in view

Viewed 714

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?

3 Answers

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 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>
}

best variant is -

<html>
    <head>
        <link rel="stylesheet" href="styles.css">       
    </head>
    <body>
        <!-- here is page content -->             
        <script src="scripts.js" type="text/javascript"></script>
    </body>
</html>

in this case browser will load in this sequence

  1. styles
  2. content (which will be already styled)
  3. scripts (which will not slow down page rendering in case if scipts are not so little)
Related