-
Notifications
You must be signed in to change notification settings - Fork 13
/
getEmPixels.js
41 lines (33 loc) · 1.45 KB
/
getEmPixels.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*! getEmPixels | Author: Tyson Matanich (http://matanich.com), 2013 | License: MIT */
(function (document, documentElement) {
// Enable strict mode
"use strict";
// Form the style on the fly to result in smaller minified file
var important = "!important;";
var style = "position:absolute" + important + "visibility:hidden" + important + "width:1em" + important + "font-size:1em" + important + "padding:0" + important;
window.getEmPixels = function (element) {
var extraBody;
if (!element) {
// Emulate the documentElement to get rem value (documentElement does not work in IE6-7)
element = extraBody = document.createElement("body");
extraBody.style.cssText = "font-size:1em" + important;
documentElement.insertBefore(extraBody, document.body);
}
// Create and style a test element
var testElement = document.createElement("i");
testElement.style.cssText = style;
element.appendChild(testElement);
// Get the client width of the test element
var value = testElement.clientWidth;
if (extraBody) {
// Remove the extra body element
documentElement.removeChild(extraBody);
}
else {
// Remove the test element
element.removeChild(testElement);
}
// Return the em value in pixels
return value;
};
}(document, document.documentElement));