Search code examples
cssrazor

Why do I get the error message "Element 'style' cannot be nested within element 'style'"?


I need to override some <style> elements within my Razor page so I've inserted the styles immediately after the opening code block:

@{
    ViewBag.Title = "New Account";
    Layout = "~/Views/Shared/_Layout_Form.cshtml";
}
<style type="text/css">
    #main
    {
        height: 400px;
    }
</style>

The page renders correctly in the browser but Visual Studio green squiggles at <style> complaining that:

<Validation (XHTML 1.0 Transitional): Element 'style' cannot be nested within element 'style'>

I've doublechecked the master page - no problems highlighted there.

What's Visual Studio expecting at this point? What's the correct way to override styles on a page by page basis? Via jQuery?


Solution

  • The style element cannot be nested under the <body> or child elements of the <body>, instead it should go to the <head> element of the page.

    If you try to override the styles like this, they get inserted into the default section of your layout page by @RenderBody(), which I assume is inside the <body> of the layout page, while the default styles still stay in the <head>.

    The proper way to override some part of the layout page from the content page would be something along these lines, using Razor sections:

    _layout.cshtml

    <head>
    @if (IsSectionDefined("Style"))
    {
        @RenderSection("Style");
    }
    else
    {
        <style type="text/css">
        /* Default styles */
        </style>
    }
    </head>
    <body>
    @RenderBody()
    ...
    

    page.cshtml

    @{        
        Layout = "layout.cshtml";
    }
    @section Style
    {
        <style type="text/css">        
        #main        
        {        
            height: 400px;        
        }
        </style>
    }
    <!-- Body content here -->
    ...
    

    Now if the Style section is defined on the content page, its contents will override the defaults from the layout page.

    I suggest you read more on Razor layouts and sections. A nice article on this by ScottGu can be found here.

    Regarding Visual Studio markup validation warnings

    Visual Studio has a problem when markup that makes up a single page is being split up between different files like this. In most cases there is no way for Visual Studio (or any such IDE for that matter) to know how the different page fragments will be dynamically put together in the end. So usually you can't avoid some of these warnings on a project.

    Personally I would ignore the warnings if I know what I'm doing and the resulting pages pass the markup validation (http://validator.w3.org/).

    If you really want to hide the warnings, you need to disable the appropriate validation options in Visual Studio. E.g. for HTML in Visual Studio 2012 this can be done in Tools > Options > Text Editor > HTML > Validation.