I’ve noticed that many times when a page’s content calls for tabs, the most often used approach is something like the following:
<div class="tabs"> <a href="?tab=tab1" class="tab activeTab">Tab 1</a> <a href="?tab=tab2" class="tab">Tab 2</a> <a href="?tab=tab3" class="tab">Tab 3</a> <a href="?tab=tab4" class="tab">Tab 4</a> </div>
There’s nothing inherently wrong with this approach, but it tends to involve more logic than is necessary to solve the problem. With this system, you have to write logic that tracks each individual tab’s state from request to request. Something that looks like this:
<?php
$activeTab = 'tab1';
if(isset($_GET['tab']))
{
$activeTab = $_GET['tab'];
}
$tabs = array(
'tab1' => 'Tab 1',
'tab2' => 'Tab 2',
'tab3' => 'Tab 3',
'tab4' => 'Tab 4'
);
echo '<div class="tabs">';
foreach($tabs as $tab=>$label)
{
if($activeTab == $tab)
{
echo '<a href="?tab='.$tab.'" class="tab activeTab">'.$label."</a>\n";
}
else
{
echo '<a href="?tab='.$tab.'" class="tab">'.$label."</a>\n";
}
}
echo "</div>\n";
?>
It doesn’t have to be like this. A trick I picked up (from a very talented coworker) allows for a more elegant solution.
Consider the following HTML:
<div class="tabs tab1"> <a href="?tab=tab1" class="tab tab1">Tab 1</a> <a href="?tab=tab2" class="tab tab2">Tab 2</a> <a href="?tab=tab3" class="tab tab3">Tab 3</a> <a href="?tab=tab4" class="tab tab4">Tab 4</a> </div>
Now, through the magic of CSS we can make something uh…”magic”… happen. Here’s the CSS:
.tabs { overflow: hidden; }
.tabs .tab {
float: left;
margin-left: 1px;
padding: 5px;
background: #EEE;
}
div.tab1 a.tab1,
div.tab2 a.tab2,
div.tab3 a.tab3,
div.tab4 a.tab4
{
background: #D4ED9F;
}
We can control the graphical state of the active tab simply having CSS determine a tab’s style according to its parent class.
<div class="tabs <?php echo $activeTab; ?>">
There’s likely a name for this technique that I’m ignorant to, so feel free to point it out to me. I in no way claim to have invented this method, but I do see many developers that don’t know CSS enough to leverage it like this. Hopefully this will be helpful to some of you out there.
Tags: active tab, css, tabs