Search code examples
htmlcssstylesheet

Is there a way to link in a stylesheet where the extension is not .css?


I need to dynamically link in the CSS (and JS if you know - haven't tested) but when I do that the browser is not rendering the styles?

Here is my code:

<link rel="stylesheet" href="css/test"/>

If I manually upload and save the file as test.css it then works.

<link rel="stylesheet" href="css/test.css"/>

Is there a way to say to the browser, "This is a CSS file. Please disregard that it doesn't have a css extension"?

MORE
The reason is I'm setting up a server that allows the user to create their own CSS dynamically. I'm storing this information in a database and don't want to create a physical (digital) file each time the user updates the css or a new user creates their account. So, the URL might be, href="http://somedomain.com/home.php?user=453&css=true" or something like that and that, if placed in the URL of the browser, would return the raw CSS.


Solution

  • Browsers look in the first place at the MIME-type of the content they receive, this is in principle independent of the extension of the file. The MIME type is sent by the web server as part of the HTTP header (the envelope of the file, if you will.)

    The correct MIME type for CSS stylesheets is text/css. If stylesheet files have the text/css MIME type (defined in the HTTP header), your browser will use them to apply the styles no matter what the extension.

    If the MIME type is wrong, the result is undefined: it depends on the browser and the HTML version & strictness if the style gets rendered or not. You can check the MIME type by using your browser's debugger.

    See this screenshot for an example in Chrome.

    this screenshot

    Each paragraph has color: red rule in the corresponding file, but one isn't applied. As you can see, the style in the text/plain file does get rendered, although its MIME type is not correct. The browser does give a warning. The style in the text/html file generated by PHP is not rendered (and a warning is given.)

    PHP and other scripting engines allow to manipulate the MIME type however, as I have done in the test.css.fixed.php file (code below.) As you can see, the browser no longer complains and applies the styles regardless of its extension.

    In PHP, the MIME type can be set as follows (this is test.css.fixed.php):

    <?php 
        header("Content-Type: text/css");
    ?>
    
        p.test_css_fixed_php {
            color: red;
        }
    

    The header function changes the HTTP header that is sent by the server.

    If you don't work with a scripting engine, you can configure your web server to set the MIME type correctly (see e.g. Apache mod_mime configuration).

    Note that the HTML version and strictness also have influence on this. In Chrome, styles in a text/html file seem to get rendered anyway when the HTML type is not strict. But you cannot count on that, so it's a quick & dirty fix at best.