[Javascript] Width Percentage to Pixel
Here is an interesting and sometimes practical question:
How do I know the 1% width of browser window equal to how many pixels?
The answer is easy: add a div element right after the body tag, make it 100% wide, and get the offsetWidth property of the div. From the value of offsetWidth property, we will know 100% width equal to how many pixels, and hence we can know 1% equal to how many pixels.
Source Code for Demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>[JavaScript] Width Percentage to Pixel example</title> </head> <body> <div id="width" style="width: 100%"> </div> <div id="info"></div> <script type="text/javascript"> var width = document.getElementById("width").offsetWidth; var info = document.getElementById('info'); info.innerHTML = 'The 100% width of browser window is ' + width + ' pixels.<br />'; info.innerHTML += '1% = ' + width / 100 + 'pixels.'; document.getElementById("width").parentNode.removeChild(document.getElementById("width")); </script> </body> </html> |