使用CSS在容器中均匀分布元素的方法今天在Smashing杂志上出现。
A method to distribute elements evenly in a container using CSS appeared on Smashing Magazine today.
我最近不得不使用Javascript实现效果的元素的可变宽度,但在SM上提出的方法让我想知道是否可以这样做没有Javascript。
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.
有这个问题,其中 gargantaun 说:
IMHO,你可能不想听到这个,但是设计可能有缺陷。常见的知识是,使用CSS在布局中均匀分布项目是一个痛苦,所以设计师应该避免。
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.
但我不能告诉设计师改变他的设计,我不同意CSS的缺点应限制设计师。
But I can't tell the designer to change his design, and I don't agree that the shortcomings of CSS should limit designers.
无论如何,这里是我在HTML(翻译和简化):
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; }和Javascript中:
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' }); }这里有一个缩小的截图(看看菜单如何与标题对齐image):
And here's a scaled-down screenshot (see how the menu aligns with the header image):
任何想法如何在没有Javascript的情况下实现这一点?
Any idea how I can achieve this without Javascript?
推荐答案元素。这是悲伤和热闹的同时看到人们把自己变成一个哥德式结与CSS,他们中的大多数人甚至不知道为什么他们避免表。
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.
无论什么原因,你可能梦寐以求拒绝表,它不可能比根据JavaScript来布局您的页面更糟。
Whatever reason you might have dreamed up to reject tables, it can't possibly be worse than depending on Javascript to layout your page.
是的,我知道这不是你正在寻找的答案,但是golly,这是显而易见的。
Yes, I know this is not the answer you were looking for, but golly, it's so obvious.
更多推荐
使用CSS均匀分布元素
发布评论