Note that there are some explanatory texts on larger screens.

plurals
  1. PODistribute elements evenly using CSS
    primarykey
    data
    text
    <p>A method to distribute elements evenly in a container using CSS <a href="http://www.smashingmagazine.com/2009/03/23/ask-sm-equal-spacing-css-image-replacement-max-side-on-images/" rel="nofollow noreferrer">appeared on Smashing Magazine</a> today.</p> <p>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.</p> <p>There's <a href="https://stackoverflow.com/questions/601096/distributing-inline-elements-using-css">this question</a>, where <a href="https://stackoverflow.com/users/64586/gargantaun">gargantaun</a> says:</p> <blockquote> <p>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.</p> </blockquote> <p>But I can't tell the designer to change his design, and I don't agree that the shortcomings of CSS should limit designers.</p> <p>Anyway, here's what I have in HTML (translated and simplified):</p> <pre><code>&lt;div id="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/news"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/theme"&gt;Theme&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/activities"&gt;Activities&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>in CSS (irrelevant properties removed and simplified):</p> <pre><code>#menu li { float: left; margin-right: 20px; } #menu a { display: block; padding: 0 1em; } </code></pre> <p>and in Javascript:</p> <pre><code>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' }); } </code></pre> <p>And here's a scaled-down screenshot (see how the menu aligns with the header image):</p> <p><a href="http://i41.tinypic.com/2ntguf8.png" rel="nofollow noreferrer">screenshot http://i41.tinypic.com/2ntguf8.png</a></p> <p>Any idea how I can achieve this without Javascript?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload