Consider a simple CSS layout, where containing wrapper div defines a fixed width of 900 or 开发者_如何学运维so pixels, everything inside it therefore expands to 100% width.
In here, I have a navigation div, containing 1 UL and 6 list items, left-floated so they appear in a line horizontally.
Each list item should growing variably to fit its text contents exactly, but the spacing between each item should be shared so that the whole menu fits into the 100% space, such as:
------------------------------------------------------
-N- -N- -N- -N- -N-
- - - - - - - - - -
- -ITEM1111- -ITEM222222- -ITEM33333333333- -ITEM44- -
- - - - - - - - - -
------------------------------------------------------
<-------------------- 100% -------------------------->
I hope that is illustrative! 'N' is constant but grows to fit the 100% width accordingly (i.e. for accessibility - someone increases the font size).
Happy to take alternative suggestions although I'm aiming for no javascript or images, just css purity.
Here is my simple solution for this based on CSS3 Flexible Box Layout:
Styles
ul {
padding: 0;
width: 100%;
}
ul li {
list-style: none;
text-align: center;
border: 1px solid Gray;
}
.flexmenu {
display: -webkit-box;
display: -moz-box;
display: box;
}
.flexmenu li {
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
-webkit-flex-basis: auto;
-moz-flex-basis: auto;
flex-basis: auto;
}
HTML
<div style="width:900px">
<ul class="flexmenu">
<li>short</li>
<li>looooooooooooooooooooooooooooooong</li>
<li>short</li>
<li>short</li>
</ul>
</div>
Result
If IE6/IE7 compatibility is not critical to you, this layout is trivial using display: table
http://jsfiddle.net/5SFG5/
Problem is that when an element is floated, its width is reduced to the actual width of the content. You can toy with this using Javascript though (I know you requested a no-js version, but I can't think of another option). In jQuery it should be fairly easy. Given this structure:
<ul id="nav">
<li>ITEM1</li>
<li>ITEM2</li>
<li>ITEM3</li>
</ul>
you could do something like this:
var width = 0, maxwidth = 900;
$('#nav li').each(function(){
width += $(this).width();
});
var count = 2 * $('#nav').size();
var margin = (maxwidth - width) / count;
$('#nav li').css({
marginLeft: margin + 'px',
marginRight: margin + 'px'
});
Sorry for the messy code, I'm in a bit of a hurry :D. Anyways, what you do is, basically: check the total width occupied by the li
elements, check how much is unoccupied and fill it with li
margins.
I'm not sure how N can be both a constant and a variable width.
Here's a start..
CSS
#nav { width: 100%; display: inline; }
#nav ul li {
display: block;
float: left;
margin: 2%;
width: 10%;
}
#nav ul li a {margin: 0 auto; display: block;}
html
<div id="nav">
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 1</a></li>
</ul>
</nav>
精彩评论