Sunday, September 14, 2008, 06:47 PM - Web
Having a line of text which is as wide as its container width, sound simple? Well, actually it is not that easy.For my pic a day gallery I wanted to put a navigation interface under the thumbnails, and to have this navigation interface extend to the full possible width. Of course, as the width changes according to the browser window, it can not be specified in pixels.
A possibility would be to use a single row table, and to put each navigation element within an individual table cell, but first it is far from an elegant solution, second I did not thought about this possibility when doing the navigation interface.
As the navigation interface is made from text elements, I thought about simply using the text-align: justify CSS property. However, this doesn't justify the last line of a paragraph, and in my case the navigation interface is a single line. CSS3 is supposed to address this issue, by the text-align-last property, which allows to set justification method for the last line of a paragraph. Problem: it is not yet supported by browsers.
So here is the trick: using Javascript to increase spacing between words, until it fills the whole container width.
First, set a small words spacing, then iteratively increase it. While doing this, check the element height. When the height increase, it means that your text was wrapped over a new line. You can then roll back words by one step, and you are done: your line now fills the whole width:
function expandNavigation() {
document.getElementById('config').style.opacity = 0;
navi = document.getElementById('navigation');
navi.style.opacity = 0;
var h0 = navi.scrollHeight;
var em = 0.2;
var em_inc = 0.2;
do {
em += em_inc;
navi.style.wordSpacing = em + 'em';
} while (navi.scrollHeight == h0)
em -= em_inc;
navi.style.wordSpacing = em + 'em';
fadeIn('navigation', 0, 15);
fadeIn('config', 0, 15);
}
In order to avoid flickering while the word spacing is increased, I also hid the text while iterating, and only made it visible again at when the optimal word spacing is found (the function fadeIn sets the text back to its visible state).
Comments are not available for this entry.

Calendar



