duancheng6500
2015-01-16 03:13
浏览 163
已采纳

如何在php中插入css代码?

I know how to insert html code in php using print <<<HERE HERE; construction. It means I can insert a link to css file. But is it possible to insert css code itself?

图片转代码服务由CSDN问答提供 功能建议

我知道如何使用 print&lt;&lt;&lt;&lt; HERE HERE < / code>建设。 这意味着我可以插入一个到css文件的链接。 但是可以插入css代码吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • donglv6747 2015-01-16 04:11
    已采纳

    There are a couple of ways you can achieve this.

    Lets say you have an anchor tag <a href="..">My Href</a> and you want to add CSS to it based on certain instances.

    You can easily echo that css into the anchor element like so:

    <a <?php echo 'style="float: left;"'; ?> href="..">My Href</a>

    The output would be: <a style="float: left" href="...">My Href</a>

    You can do this with almost any HTML element.

    Now let's say you have a predefined CSS class you would like to echo into an anchor tag element.

    Let's say you have this CSS class in your stylesheet:

    .floatLeft {
        float: left;
    }
    

    You can simply echo that class into the anchor element like so:

    <a href="..." class="<?php echo 'floatLeft'; ?>">My Href</a>

    Which the output of that would be:

    <a href="..." class="floatLeft">My Href</a>

    点赞 打赏 评论
  • dsifjgogw48491752 2015-01-16 03:20

    Yes. It is possible.

    There's actually two different ways.

    Method 1: Inject PHP into your actual CSS. This is done by making your file .php, using regular HTML and CSS, and then doing as such:

    .someclass {
    /* Some code */
    <?php // Whatever you wanna inject 
    ?>
    

    I have performed this many times, and no one knows. It may not be the most efficent way, but it's also sometimes better than doing...

    Method 2: Escape your quotes and lines.

    Use:

        echo("/* Your css code here */ \ (to escape the line return
            /* Whenever there is a quote, make sure to do the following: \" ");
    

    If you don't escape the quote, PHP will think you're ending the string. That's bad, because the rest of your text gets ignored.

    ADDITIONAL NOTE: You don't have to use print for echoing HTML. Echo works too.

    点赞 打赏 评论
  • douliaopan1419 2015-01-16 05:10

    Yes, you can easily do that. You can either do it in the CSS file like 'ilarsona' said, or you can do it in the HTML file itself.

    For example:

    <!DOCTYPE html>
    
    <html>
    
        <head>
            <title>The Title</title>
            <style>
                p {<?php *Insert dynamic styles here* ?>};
            </style>
        </head>
    
        <body>
            <div style=<?php *Insert styles here* ?>> </div>
        </body>
    
    </html>
    
    点赞 打赏 评论

相关推荐 更多相似问题