7

I am trying to create a navigation panel for my website. I would like it to consist of:

  • Four tabs in equal size with text-centered in each tab.
  • They should fill the whole page width.

I would really like the design to be flexible and browser friendly. I have tried various float techniques, but I can't get it to work. I hope that you can help me out!

Thank you.

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
nodesto
  • 505
  • 2
  • 8
  • 24

3 Answers3

18

HTML

EDIT: it's 2015 and HTML5 has been there for a while; following code should be inside a nav element (html5doctor) with landmark ARIA attribute role="navigation" on it (and 99.9% of the time be unique in any given page).

A navigation panel should use an unordered list of links:

<ul id="nav">
  <li><a href="#">One</a></li>
  <li><a href="#"> Second</a></li>
  <li><a href="#">Third</a></li>
  <li><a href="#">Fourth and last, so large that... worst case</a></li>
</ul>

CSS

EDIT2: It's 2017, just use Flexbox (with or without flex-wrap: wrap)

inline-block is useful but has one drawback: whitespace between two elements must be carefully managed. Whether removed or no </li> in HTML5 or </li> at the beginning of the following line stuck like </li><li>next item or other tricks, you still have to do something or it'll create a ~4px gap between 2 elements.

25% + 25% + 25% + 25% doesn't equal 100% on all browsers if the total isn't a multiple of 4. Each browser has its own rounding method.

If you want elements to total 100% width and equal width, another method is to use display: table (and table-cell) with table-layout: fixed to force browsers to use the other table algorithm, the one that doesn't try to adapt cells width to content but respect the widths wanted by the designer/developer as far as possible.

ul {
  margin: 0;
  padding: 0;
}
li {
  list-style-type: none;
}
#nav {
  display: table;
  table-layout: fixed;
  text-align: center;
}
#nav li {
  display: table-cell;
  width: 25%;
  padding-right: 1px;
  height: auto;
  vertical-align: bottom;
}
#nav a {
  display: block;
  min-height: 100%;
  padding: 4px 10px;
  background-color: #222;
  color: white;
  border-radius: 6px 6px 0 0;
}

Fiddle

http://jsfiddle.net/PhilippeVay/aHCy3/1/
edit: http://jsfiddle.net/PhilippeVay/aHCy3/2/ with another method for space between each tab, courtesy of my colleague.

FelipeAls
  • 21,711
  • 8
  • 54
  • 74
  • Oops, in fact I forgot to remove the 2 other `.tab` from their respective list item. As there's an id `#nav` on `ul`, this class isn't needed anymore, li are styled with the selector `#nav li`. Fiddle, link and HTML code edited. – FelipeAls Aug 19 '12 at 10:37
  • 1
    another method for space between each tab: see the new fiddle (with `border-spacing`) – FelipeAls Aug 22 '12 at 15:01
  • You're awesome, I have been stuck on this for a bit. – mario Jul 01 '14 at 20:31