如何动态更改CSS

I need my administrator to be able to change/update the banner of my site.

This is the banner code

<div class="containertop">This depends on the background of the div</div>

and this is the CSS for that

.containertop
{
     width:1000px;
     height:300px;  
     **background:url(../images/1.png) no-repeat center;**
     margin: 0 auto;
     margin-top: 40px;
}

What I would like to happen is the same as a Facebook cover photo. When a new banner is uploaded, the CSS will be updated(something like that). But of course, the new banner must be fetched from the database.

So I am thinking that the CSS would become like this:

Fetch the saved banner source and then:

background:url(<?php echo $row['image']; ?>);

but can I do the PHP connection to database (include 'dbname.php') inside a CSS txt?

I agree with Ben. If you make a little embedded css section in your page, you could put the .containerTop css code there. Then, put your code in the page. So, in your actual web page, put this:

<style type="text/css">
.containertop{
width:1000px;
height:300px;  
background:url(<?php echo $row['image']; ?>);
margin: 0 auto;
margin-top: 40px;
}
</style>

Of course, your background url will not update until it is reloaded. If you decide to do it this way, don't forget to take the .containerTop definition out of your existing css. Having said all that, I really like dystroy's answer. Very nice. I never thought of doing that.

There's nothing preventing you to serve a css generated by PHP. That's even easy.

Simply start your php file like this :

<?php
header("Content-Type: text/css");

You can set containertop background while loading php file.

<?php
echo "<style>.containertop{ background:url(../images/".$row['image'].") no-repeat center;}</style>"
?>

This will set the background fetched from db.

Well, You can use jQuery to change/overwrite the CSS file.

Example -

$('.containertop').css('backgroud','url(images/change.jpg) repeat');

or

$('.containertop').css('backgroud','url(<?php echo $images_url ?>) repeat');