How to Change CSS Dynamically

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?

Answers


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');

Need Your Help

How do I deploy an ASP.NET MVC web site using Visual Web Developer 2010 Express Edition?

asp.net asp.net-mvc visual-studio-2010 asp.net-mvc-2

I'm having problems deploying my website to the live server using VWD 2010 Express. I had done this without a problem in VWD 2008 Express. But, it seems that the tools for publishing a site are very

Why do I get System.IO.FileLoadException: Could not load file or assembly, about once a week on my ASP.Net Website?

c# asp.net assemblies enterprise-library fileloadexception

I have a rather simple internal ASP.Net Website that has issues loading the Microsoft.Practices.EnterpriseLibrary.Data dll about once a week. Here is the Exception message: