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?
Of course this is exactly what the table element is for. It's sad and hilarious at the same time to see people twist themselves into a gordian knot with CSS, most of them not even knowing why they're avoiding tables.
Whatever reason you might have dreamed up to reject tables, it can't possibly be worse than depending on Javascript to layout your page.
Yes, I know this is not the answer you were looking for, but golly, it's so obvious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With