Skip to content

Instantly share code, notes, and snippets.

@jackprice
Created December 28, 2013 16:20
Show Gist options
  • Save jackprice/8161160 to your computer and use it in GitHub Desktop.
Save jackprice/8161160 to your computer and use it in GitHub Desktop.
Borrowing from Android, allows you to use the device-independant pixel unit (dp) in CSS stylesheets.
(function(){
var dpi;
function get_dpi(){
var div = document.createElement("div");
div.style.visibility = "hidden";
div.style.width = "1in";
div = document.body.appendChild(div);
var dpi = div.clientWidth;
div.parentElement.removeChild(div);
return dpi;
}
function parse(style){
return style.replace(/[0-9]+(?:dp)(?=\W)/g, function(match){
var dp = parseInt(match);
return dp * (dpi / 160) + "px";
});
}
function init(){
dpi = get_dpi();
var stylesheets = document.styleSheets;
for (var i = stylesheets.length - 1; i >= 0; i--) {
stylesheets[i].ownerNode.innerHTML = parse(stylesheets[i].ownerNode.innerHTML);
};
}
window.addEventListener("DOMContentLoaded", init, false);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment