outaTiME

at devel days

Computed vs Cascaded Style

leave a comment »

Just as the panel discussed getComputedStyle and how each browser returns something different, Erik Arvidsson blogged about Computed vs Cascaded Style.

Erik discusses the difference between computed, cascaded, and override styles. He shows us why this common function is bad:

JAVASCRIPT:

  1.  
  2. function getStyle(el, prop) {
  3.   if (document.defaultView && document.defaultView.getComputedStyle) {
  4.     return document.defaultView.getComputedStyle(el, null)[prop];
  5.   } else if (el.currentStyle) {
  6.     return el.currentStyle[prop];
  7.   } else {
  8.     return el.style[prop];
  9.   }
  10. }
  11.  

Back to our earlier question. What is wrong with our getStyle function? It
should be pretty obvious now. It will give very different and sometimes
unexpected results depending both on browsers and on the value set by the page
author and even worse, set by user style sheets.

So how do we solve this? We stop supporting IE of course… seriously, with
the market share IE has that is not an option. The best solution is to remove
functions like these from shared code and instead add more specific functions.
One can for example, often calculate the computed value based on the cascaded
value and the ancestors. A good example of that is ‘visibility’. Computing that
is pretty easy. If the value is ‘inherit’ check the parents until a non inherit
value is found. For things like left, width etc you will be better of using
offsetLeft, offsetWitdh etc. There are a lot of cases and sometimes it is just
not possible (or requires iterative testing with different absolute sized
elements).

Dean Edwards then commented with the following:

JAVASCRIPT:

  1.  
  2. var PIXEL = /^\d+(px)?$/i;
  3. function getPixelValue(element, value) {
  4.   if (PIXEL.test(value)) return parseInt(value);
  5.   var style = element.style.left;
  6.   var runtimeStyle = element.runtimeStyle.left;
  7.   element.runtimeStyle.left = element.currentStyle.left;
  8.   element.style.left = value || 0;
  9.   value = element.style.pixelLeft;
  10.   element.style.left = style;
  11.   element.runtimeStyle.left = runtimeStyle;
  12.   return value;
  13. };
  14.  

(Via Ajaxian.)

Written by outaTiME

July 30, 2007 at 10:48 am

Posted in CSS, Development

Leave a Reply