如何使用php变量对css进行后台处理


How to background css with php variable

我只有这个css样式。

<style>
    #weatherblock{
    font-family:"Futura Md", "Futura Md BT";
    color:rgba(51,51,51,1);
    background-image:url("VARIABLE HERE");
    background-repeat:no-repeat;
    border-radius:20px;
    position:absolute;
    left:0px;
    top:0px;
    width:400px;
    height:220px;
    background-size:cover;
    z-index:5;
    font-size:20px;
    vertical-align: top;
    }
</style>

我想把一个可变的图像放在"这里可变"的地方。我不知道是放$img还是放'$img$。我也不知道如何定义img的变量。$img = 'img.png';??

感谢

只需放置PHP代码。

<?php
$img = 'img.png';
?>
<style>
#weatherblock{
font-family:"Futura Md", "Futura Md BT";
color:rgba(51,51,51,1);
background-image:url("<?php echo $img ?>");
background-repeat:no-repeat;
border-radius:20px;
position:absolute;
left:0px;
top:0px;
width:400px;
height:220px;
background-size:cover;
z-index:5;
font-size:20px;
vertical-align: top;
    }
</style>

它将被$img取代。显然,它必须是一个.php文件。

我不建议通过服务器端代码将变量注入CSS定义中(无论如何,大部分CSS都应该在外部样式表中)。

两者都有不同的背景:

在样式表中

.background-1 {
    background-image: url(image1.jpg);
}
.background-2 {
    background-image: url(image2.jpg);
}

在HTML 中

<div class="background-<?php echo $background; ?>">
    // Something
</div>

或者使用CSS内联:

<div style="background-image: url(<?php echo $background; ?>);">
// Something
</div>