GetRealComputedStyle

Getting the real computed style of a block element without the need of rendering it

by GerĂłnimo Garcia Sgritta

HTML

<div id="box"></div>
<ul id="console">
    <li>Console</li>
</ul>

CSS

.test {
    display:none;
    height: 40px;
    width: 50px;
}

JavaScript

function log(msg){
   var li = document.createElement('li');
   var text = document.createTextNode(msg);
   li.appendChild(text);
   document.getElementById('console').appendChild(li); 
}

function getRealDimensions(selector){
    var d = document;
    var b = d.body; 
    var dv = d.defaultView;
    var isId = /^#.*$/.test(selector);
    var el, w, h;
    
    
    el = d.createElement('div');
    isId ? el.id = selector : el.className = selector;
    
    b.insertBefore(el, null);
    el.style.display = 'none';

    if(dv.constructor.prototype.getComputedStyle){
        w = dv.getComputedStyle(el, null).getPropertyValue('width');
        h = dv.getComputedStyle(el, null).getPropertyValue('height');       
    } else {
        w = el.currentStyle['width'];  
        h = el.currentStyle['height'];
    }
    
    w = w.replace('px', '');
    h = h.replace('px', '');
    
    return {
        width: w,
        height: h
    }
}

log('hi!');

var dim = getRealDimensions('.popup');

log(dim.width);
log(dim.height);