Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

javascript - Distribute elements evenly using CSS

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):

screenshot

Any idea how I can achieve this without Javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...