5

I have been trying to implement Chris Coyier's inline-block + text justify solution to automatically distribute div's horizontally in a given wrapper's width. http://css-tricks.com/equidistant-objects-with-css/

This works great when the elements are imediately loaded into the DOM but for some reason fails when adding elements programattically through JS. It's as if the browser just ignores the css properties.

Check out this fiddle for a very basic example: http://jsfiddle.net/xmajox/NUJnZ/ The first two rows are added on HTML load. Click the button to add more in run time through JS.

Initially I thought it could be somehow related to the use of pseudo-element :after so I tried a different version with a DOM node instead: http://jsfiddle.net/xmajox/wnPSA/ Unfortunately it reacts exactly the same way.

Anyone has any idea why this happens? or better yet, how to fix/prevent it?

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
Rodrigo Neves
  • 220
  • 2
  • 12

1 Answers1

7

There needs to be some form of whitespace between the elements for this to work, see this: http://jsfiddle.net/NUJnZ/22/

Notice in the third row that there's no space between the DIVs. When jQuery appends the new element there's no leading or trailing whitespace.

Simply add a trailing space with .before(' ') and the elements line up properly. (if you use .after(' ') there's a spacing issue on the last element)

Updated fiddle: http://jsfiddle.net/NUJnZ/24/

Snuffleupagus
  • 6,365
  • 3
  • 26
  • 36
  • Wow, great catch, I was nowhere near. Is this 'normal' behaviour for a browser? I thought it didn't matter at all... – Rodrigo Neves Oct 10 '12 at 15:13
  • @xmajox Well, I wouldn't call it a bug, it's standard. Check out [this](http://jsfiddle.net/DksVF/). I'm not exactly sure why the whitespace is necessary, I'm guessing it just lumps it into one element and thinks it only has one thing to justify without it. – Snuffleupagus Oct 10 '12 at 15:20
  • Of course! It has to do with the nature of how text justification works... the text-align: justify spreads the 'words' equally based on spaces: no spaces, it's all one word for him. Thanks for the help! – Rodrigo Neves Oct 10 '12 at 15:26
  • The battle goes on... check out http://stackoverflow.com/q/12834369/1735214 if you have a few minutes ;) – Rodrigo Neves Oct 11 '12 at 07:30