Swap banner image with CSS and PHP
September 14, 2005
/ Filed under: CSS, PHP, Tutorials, Web Development
Let’s say I have a site template set up, and included within that template is a header, which is just a simple banner image, much like the one on this site:
This banner image is part of the template, so if I make a change to the banner image, every page reflects this change. I only have to make changes once. However, let’s say there’s some sections of my site that need a different banner image. It could be just a slight adjustment to the current banner image - or it could be a completely new banner image. Since my header (which contains the banner image) is hard-coded to the template system, how would I allow for different images to be swapped in, depending on the section of the site? Well... to start - using your native server-side scripting language, you can test to see which section of the site the viewer is currently at. This "test" is different for everyone. It all depends on how your CMS is set up. For me, it simply involves checking the URL for the appended directory - something like: Then, with CSS, you can write a custom ExampleSo, here’s the HTML for my header, in the template:
<div id="header">
<h1><a href="/">Web Site Name</a></h1>
</div>
And here’s the corresponding CSS:
#header
{
background: url(/images/header.gif) no-repeat;
height: 159px;
width: 791px;
}
#header h1
{
display: none;
}
As you can see, the To swap in a different header image, we have to change the selector, which is currently Then, once the selector is changed, we write another CSS rule to match that selector, and apply a different image. PHPAgain, using the example URI:
<?php
if ( $url == "contact" )
{
$header = "<div id='header' class='contact'>";
}
else
{
$header = "<div id='header'>";
}
?>
Notice the CSSAll we have left to do is write the CSS to match the So, adding to the code from above:
#header
{
background: url(/images/header.gif) no-repeat;
height: 159px;
width: 791px;
}
#header h1
{
display: none;
}
#header.contact
{
background: url(/images/header-contact.gif) no-repeat;
}
Notice the alternate image that is pulled: You can do this for as many pages as you’d like. All you need to do is create a new class for each one.
Comments/Mentions
|
Editor Picks
Email NewsletterSubscribe to the digest newsletter to receive posts by email: Recent Comments
Advertisements
|
Matt, is there a way to do this based on page_id?