Home The Yankee Webshop

Practical Code Length Values in Webpages

by Kenneth Tibbetts

Length and size values, applied as style properties or attributes of html document elements, must be strings, not primitive numbers. 

Lengths and sizes may be passed as absolute or relative values.

These strings need a number and a constant signifying the units.

(In the examples, left and top apply to positioned elements.)

There is one common exception to this rule- units are not always necessary with line-height: 

el.lineHeight='1.5' is equivilent to el.lineHeight='150%'. 

You may also specify a percentage of the available space in the element's containing parent:

Font elements also allow integer+ 'pt' for points, ('12pt') or one of these constants:

You may also use 'larger' or 'smaller'. The calculation will be on the inherited value of the element. 

When you query an html element to retrieve its displayed size, the returned value will be a string.  If you need to manipulate the size of an element:

  1. you will need to determine the units, 
  2. extract the numerical value,  
  3. perform your calculations, 
  4. and convert the final value to a string with the proper units. 

This example shows how you might reduce the width of an element by one half:

// For example, you call: halfSizer(wot);

// wot is a reference to an element in the document

function halfSizer(wot){

if(!wot || !wot.style) return;  

//  belt and suspenders code. If you need to support  
// browsers that have no style object, you could

// branch for them from here. Or just skip them.

 

var x=wot.style.width ;

// For example,  x="500px";

var whereU=x.search(/[^d]/);

// finds the index of the first non-digit in the string. 
// in this example whereU=  3, the 'p' position.

var units=x.substring(whereU);

// Extracts the units. Here, units='px'. 

newSize=Math.round(parseFloat(x)*.5));

// Now you can work with the numbers. 

 

newSize= newSize+ units;

element.style.width= newSize;

//The value of newSize in this example is "250px".

 

return newSize;

// you have already done the resize,

// but the return value is sometimes useful.

}

The Yankee Webshop

tech@yankeeweb.com