views:

206

answers:

3

I'm trying to achieve a horizontal CSS menu bar where all of the <a> elements combined expand to the entire width of the parent. The HTML looks something like this:

<div id="parent">
    <a href="/">Home</a>
    <a href="/learn">Learn More About The Product</a>
    <a href="/about">About Us</a>
    <a href="/contact">Contact Us</a>
</div>

The idea is each of the four <a> elements above take up some % of the total width so that the left side of Home and the right side of Contact Us line up with the edges of parent. They can't take up exactly 25% each or else "Learn More About The Product" would look goofy because it is too long.

Any ideas?

+2  A: 

While there's no direct way in CSS of saying, "Automatically position these across the screen occupying the full width" (in the way the cells of a table will automatically resize themselves), you can still give the widths as explicit percentages:

<div id="parent">
    <a href="/" style="width: 20%;">Home</a>
    <a href="/learn" style="width: 40%;">Learn More About The Product</a>
    <a href="/about" style="width: 20%;">About Us</a>
    <a href="/contact" style="width: 20%;">Contact Us</a>
</div>
VoteyDisciple
I'm trying so hard to be a good guy and not use tables for layout, but it keeps biting me! :)
JerSchneid
+2  A: 

You can deal it by langauge in which you are generating your pages

You can count lenght of the strings together and then by particular string legth get the percentual part of whole menu.

The script which is counting

<?php
// percentageCounter.php
$menuItems = array(
 'home'=>array('label'=>'Home'),
 'learn'=>array('label'=>'Learn More About The Product',),
 'about'=>array('label'=>'About Us',),
 'contact'=>array('label'=>'Contact Us',),
 'str_len_sum' => 0,
);
foreach($menuItems AS $key => $menuItem)
{
  $menuItems['str_len_sum'] += strlen($menuItem['label']);
}

foreach($menuItems AS $key => $menuItem)
{
  $menuItems[$key]['percentage'] = (100/$menuItems['str_len_sum'])*strlen($menuItem['label']);
}

And the one which is printing menu

<?php //menuOutput.php
require_once 'percentageCounter.php';
?>
<div id="parent">
<?php foreach($menuItems AS $key => $menuItem): ?>
    <a href="/<?php echo $key ?>" style="width: <?php echo $menuItem['percentage'] ?>%;"><?php echo $menuItem['label'] ?></a>
<?php endif; ?>
</div>
Mailo
A: 

I guess it depends on the requirements (IE6...), but you could try using:

#parent {
    display: table-row;
}
#parent a {
    display: table-cell;
}

I haven´t tried it, but I think that should give it a table-like behaviour.

jeroen
It's a good try, but with neither IE6 nor 7 supporting it we're not quite there yet. I think in this case there's no shame in using an actual table in the meantime.
bobince
Yes, that's probably what I would do as well :-)
jeroen