Where's My Style?

Sorry... this article is currently very simple and unfinished. I'll try to get back to it as soon as I can.

The Problem

Summary

The properties of element.style correspond to the HTML element's inline STYLE attribute - NOT to any styles applied by its id or class attributes. For example...

<html>
<head>
<style>
#e1 {
  position:absolute;
  background:#00f;
  left:100px; top:100px;
  width:100px; height:100px;
}
#e2 {
  position:absolute;
  background:#f00;
  width:100px; height:100px;
}
</style>
<script>
window.onload = function() {
  showPosition('e1');
  showPosition('e2');
}
function showPosition(id) {
  alert(
    "Position for " + id + ":\n"
    + "\nstyle.left = " + document.getElementById(id).style.left
    + "\nstyle.top = " + document.getElementById(id).style.top
  );
}
</script>
</head>
<body>
<div id='e1'></div>
<div id='e2' style='left:200px; top:200px;'></div>
</body>
</html>

Visually, both elements are positioned properly. However, the first alert box will display no values because the value of each property is an empty string. The second alert box will display a value of "200px" for left and top.

Other CSS properties operate the same way.

Solutions

Design

Since you know that element.style.property will initially be an empty string you can design your script so that it doesn't rely on the property having an initial value.

getComputedStyle

More browsers are now supporting the getComputedStyle method of the document.defaultView object. For a cross-browser version of this method see xGetComputedStyle. Note that it has limitations when used in IE (which does not support getComputedStyle).

offsetXXX Properties

Originally these were IE4 object model properties. Now they are supported by many of the newer browsers - but not without some quirks.

Set Before Get

You can make sure you set a property before getting it. That is, if you're going to hard-code a position in the CSS, then also hard-code it into the initialization of the element in script.

Tech Support

Forum support is available at the X Library Support Forums.

Search

Cross-Browser.com

World Wide Web