How to import/include a CSS file using PHP code and not HTML code?

后端 未结 14 1808
無奈伤痛
無奈伤痛 2020-11-28 11:11

I have googled a lot but it seems that I am doing something wrong.

I want to do this:



        
相关标签:
14条回答
  • 2020-11-28 11:31

    You have to surround the CSS with a <style> tag:

    <?php include 'header.php'; ?>
    <style>
    <?php include 'CSS/main.css'; ?>
    </style>
    ...
    

    PHP include works fine with .css ending too. In this way you can even use PHP in your CSS file. That can be really helpful to organize e.g. colors as variables.

    0 讨论(0)
  • 2020-11-28 11:31

    To use "include" to include CSS, you have to tell PHP you're using CSS code. Add this to your header of your CSS file and make it main.php (or styles.css, or whatever):

    header("Content-type: text/css; charset: UTF-8");
    

    This might help with some user's connections, but it theoretically (read: I haven't tested it) adds processor overhead to your server and according to Steve Souder, because your computer can download multiple files at once, using include could be slower. If you have your CSS split into a dozen files, maybe it would be faster?

    Steve's blog post: http://www.stevesouders.com/blog/2009/04/09/dont-use-import/ Source: http://css-tricks.com/css-variables-with-php/

    0 讨论(0)
  • 2020-11-28 11:32

    I don't know why you would need this but to do this, you could edit your css file:-

    <style type="text/css">
    body{
    ...;
    ...;
    }
    </style>
    

    You have just added here and saved it as main.php. You can continue with main.css but it is better as .php since it does not remain a css file after you do that edit


    Then edit your HTML file like this. NOTE: Make the include statement inside the tag

    <html>
    <head>
     <title>Sample</title>
     <?php inculde('css/main.css');>
    </head>
    <body>
    ...
    ...
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 11:33

    You could do this

    <?php include("Includes/styles.inc"); ?>

    And then in this include file, have a link to the your css file(s).

    0 讨论(0)
  • 2020-11-28 11:35

    _trace its directory, I guess

    echo css('lib/datatables_rqs/jquery.dataTables.css');
    
    0 讨论(0)
  • 2020-11-28 11:36

    you can use:

    <?php
    $css = file_get_contents('CSS/main.css');
    echo $css;
    ?>
    

    and assuming that css file doesn't have it already, wrap the above in:

    <style type="text/css">
    ...
    </style>
    
    0 讨论(0)
提交回复
热议问题