230
votes

I've got a large site that runs in ASP.NET MVC using the Razor view engine.

I have a base stylesheet which contains all of the generic styling for the whole site. On occasion, however, I have page specific styles which in the <head> of the page - usually this is one or 2 lines.

I don't particularly like putting the CSS in <head> as its not strictly separation of concerns, but for one or two lines, that really is specific to that page, I prefer not have to attach another file and add to the bandwidth.

I've got an instance though where I would like to put a page specific media query into the <head>, but because a media query uses the @ symbol and brackets {} it's clashing with the razor syntax:

@section cphPageHead{
     <style>
        /* PAGE SPECIFIC CSS */
        ...

        @media only screen and (max-width : 960px) <-- the @ symbol here is clashing!
            {
               ... }
            } 
    </style>
}  

Is there a way I can get around this?

3
I still think that, css styles should be in the CSS file, especially for a "Large site" Linear css on the page is not the best practice. PS: My opinionAlexC
I agree with @AlexC, but for those curious about a valid use case, critical CSS loads faster inline than externally. It's a pretty handy trick for those sites that rely on a super fast first meaningful paint.John Pavek
Another use case is rendering emailsJan Zahradník
For people who using a code analyzer tool like sonar double @ can be marked as a major bug by tool. If you have a chance to change or disable the rule it is ok otherwise you have to find another way to escape @.ümit Altuntaş
When using @media with grid you may want the style sheet in the page because each page layout may be different, you just want to control THAT specific page and packing away the css into a file is over-engineering and just doesn't make sense. Keep code that goes together close together in this case. So any case where the css is ABSOLUTELY just for a single page it is best in that page. Otherwise ALWAYS in a seperate css fileM H

3 Answers

530
votes

use double @@ symbols. That will escape @ symbol and render @media correctly on client side

29
votes

Also remember to add a space after double @@:

 @@ media only screen and (max-width : 960px)

@@media with no space did not work for me.

12
votes

I realize this is old question, but this is the only solution that worked for me:

@section cphPageHead{
    <style type="text/css" media="screen and (max-width:959px)">
    </style>


    <style type="text/css" media="screen and (min-width:960px)">
    </style>
}