Let's say I have a fixed width page (960px) with a nav menu across the top. The menu has 5 items of equal width, so each item's width can be 20% or 192px. Is there a way to set this up so that if I add another menu item, I don't have to manually change the width to 16.66% or 160px?

Reason I'm asking is that I'd like to set up a template in our CMS that would allow a user to add an additional menu item through the CMS admin tool without touching any code.

Can this be done purely with CSS, or must JavaScript or the underlying language for our CMS (ColdFusion) get involved?

Thanks.

P.S. For a visual example, take a look at the attached URL. Let's say I want to add another item between "Media Library" and "For Educators" only by adding HTML (and not touching existing HTML or CSS).

2 answers

2
points
This was chosen as the best answer

Given the fact that the total number of items in the menu is subject to change, there is really no good way to do this with CSS. As you stated, you can easily write some JavaSript or server-side logic to assign the CSS width based on the number of items in the menu.

In favor of simplicity, you may consider redesigning the menu so that it has room to grow, so to speak. I'm thinking the width of each menu item could be determined by its content, as opposed to each item being of equal width.

Answered almost 7 years ago by Dwayne Anderson
Mottie 1134
1
point

Your example page uses a table for the tabs. To tell you honestly, I believe using a table would be ideal for what you are asking. Set the width of the table to 100% and all cells will automatically adjust to make equal width cells (tabs). Add a new cell and the table adjusts to accommodate. So there is no need to adjust the CSS at all.

<style type="text/css">
 .wrapper { width: 100%; }
 .tab { background: #555; text-align: center; margin: 5px; }
</style>

<table class="wrapper">
 <tr>
  <td class="tab">tab 1</td>
  <td class="tab">tab 2</td>
  <td class="tab">tab 3</td>
  <td class="tab">tab 4</td>
  <td class="tab">tab 5</td>
 </tr>
</table>

To add a new tab, add a cell inside the table (e.g. <td class="tab">tab 6</td>)

You didn't specify how you were adding the new tab, but I'm guessing it's done either server side or with javascript which could also be used to adjust the sizes as you were asking. Here is how I would do this with jQuery:

<style type="text/css">
.wrapper { width: 100%; }
.tabs { float: left; background: #555; text-align: center; margin: 0; padding: 0; }
</style>

<div class="wrapper">
 <div class="tabs">tab 1</div>
 <div class="tabs">tab 2</div>
 <div class="tabs">tab 3</div>
 <div class="tabs">tab 4</div>
 <div class="tabs">tab 5</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
 var tabs = $('div.wrapper').find('.tabs');
 if (tabs.length) tabs.css('width', (100/tabs.length) + "%");
})
</script>
Answered almost 7 years ago by Mottie