A method to distribute elements evenly in a container using CSS appeared on Smashing Magazine today.
I recently had to use Javascript to achieve the same effect for elements of variable width, but the method presented on SM made me wonder if it was possible to do this without Javascript.
There's this question, where gargantaun says:
IMHO, and you probably don't want to hear this, but the design is probably flawed. It's common knowledge that distributing items evenly across a layout with CSS is a pain, so designers should avoid it.
But I can't tell the designer to change his design, and I don't agree that the shortcomings of CSS should limit designers.
Anyway, here's what I have in HTML (translated and simplified):
<div id="menu">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/news">News</a></li>
<li><a href="/theme">Theme</a></li>
<li><a href="/activities">Activities</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</div>
in CSS (irrelevant properties removed and simplified):
#menu li { float: left; margin-right: 20px; }
#menu a { display: block; padding: 0 1em; }
and in Javascript:
function justifyMenu() {
var menuItems = $$("#menu li");
var menuWidth = $("menu").getWidth();
var totalWidth = 0;
menuItems.each(function(e) {
totalWidth += e.getWidth();
});
var margin = (menuWidth - 4 - totalWidth) / (menuItems.length - 1);
margin = parseInt(margin);
menuItems.each(function(e) {
e.setStyle({ marginRight: margin + 'px' });
});
menuItems[menuItems.length - 1].setStyle({ marginRight: '0' });
}
And here's a scaled-down screenshot (see how the menu aligns with the header image):
Any idea how I can achieve this without Javascript?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…