Wednesday, August 13, 2008

Pixel To Percentage Conversion In CSS

Published September 29th, 2006 under CSS, Web Development
by Mashhoor Al Dubayan

As you might already know, Internet Explorer won’t allow its users to resize a Web Site’s text if its font-size has been defined using pixel units.

To overcome this issue, you need to define your font size using percentages. Percentages define the font size of an element relative to the font size of its parent element, which might be a bit confusing, especially if you’re used to using pixels. But I’ve recently been shown a simple trick that enables you to convert from pixels to percentages :

Most browsers set the font size to the equivalent of 16px by default. To convert the pixel value we need to percentage, we do the following :

* For a 13px text: 13 / 16 = 0.8125 = 81.25%
* For an 18px text: 18 / 16 = 1.125 = 112.5%

The examples should be self-explanatory. We just move the first three digits (from the left) of the results to the left of the floating point to get the percentage value. Note that if the element’s parent’s font-size has been set to 14px (for example), then you need to divide by 14, not 16.

I personally won’t bother with percentages just to support Internet Explorer, but this might be handy in future projects.

No comments: