Skip to content

Instantly share code, notes, and snippets.

@reinhrst
Created June 11, 2012 11:01
Show Gist options
  • Save reinhrst/2909594 to your computer and use it in GitHub Desktop.
Save reinhrst/2909594 to your computer and use it in GitHub Desktop.
Trick to use (window.innerWidth - #variable#) properties in css
/**
* allows the kind of css rules in your stylesheets that you always wanted:
* #bottom_bar {bottom: 0px; top: window.innerHeight - 50px}
* (obviously one could use height: 50px in this case, but I want to animate on the top property)
* This code (currently only tested on webkit) allows "magic values" for properties: 314151 means "width minus", 314152 means "height minus"
* #bottom_bar {bottom: 0px; top: 31415250px} // this results in the desired behaviour
* Note: only run this function after all the stylesheets have been loaded (or rerun after load of a new stylesheet)
**/
var STYLEMAGIC_WIDTH_MINUS = /^314151(\d+)(\w+)$/;
var STYLEMAGIC_HEIGHT_MINUS = /^314152(\d+)(\w+)$/;
variableWidthSettings = function () {
var i, ss, rulenr, stylesheet, rule;
variableWidthSettings.updateMethods = [];
var getWidthMinusFunction = function (rule, key, pixels_from_edge, unit) {
return function () {
rule.style[key] = (window.innerWidth - pixels_from_edge) + unit;
};
};
var getHeightMinusFunction = function (rule, key, pixels_from_edge, unit) {
return function () {
rule.style[key] = (window.innerHeight - pixels_from_edge) + unit;
};
};
for (ss = 0; ss < document.styleSheets.length; ss++) {
stylesheet = document.styleSheets[ss];
for (rulenr = 0; rulenr < stylesheet.cssRules.length; rulenr++) {
rule = stylesheet.cssRules[rulenr];
for (i in rule.style) { if (rule.style.hasOwnProperty(i)) {
var result = STYLEMAGIC_WIDTH_MINUS.exec(rule.style[i]);
if (result) {
variableWidthSettings.updateMethods.push(getWidthMinusFunction(rule, i, result[1], result[2]));
}
result = STYLEMAGIC_HEIGHT_MINUS.exec(rule.style[i]);
if (result) {
variableWidthSettings.updateMethods.push(getHeightMinusFunction(rule, i, result[1], result[2]));
}
} }
}
}
var update = function () {
var i;
for (i = 0; i < variableWidthSettings.updateMethods.length; i++) {
variableWidthSettings.updateMethods[i]();
}
};
window.onresize = update;
update();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment