class method Element.getStyle

View source on GitHub →

Element.getStyle(element, style) → String | Number | null
  • style (String) – The property name to be retrieved.

Returns the given CSS property value of element. The property can be specified in either its CSS form (font-size) or its camelized form (fontSize).

This method looks up the CSS property of an element whether it was applied inline or in a stylesheet. It works around browser inconsistencies regarding float, opacity, which returns a value between 0 (fully transparent) and 1 (fully opaque), position properties (left, top, right and bottom) and when getting the dimensions (width or height) of hidden elements.

If a value is present, it will be returned as a string — except for opacity, which returns a number between 0 and 1 just as Element.getOpacity does.

Examples
$(element).getStyle('font-size');
// equivalent:
 $(element).getStyle('fontSize');
// -> '12px'
Notes

Not all CSS shorthand properties are supported. You may only use the CSS properties described in the Document Object Model (DOM) Level 2 Style Specification.

Old versions of Internet Explorer return literal values; other browsers return computed values.

Consider the following HTML snippet:

<style>
  #test {
    font-size: 12px;
    margin-left: 1em;
  }
</style>
<div id="test"></div>

Then:

$('test').getStyle('margin-left');
// -> '1em' in Internet Explorer,
// -> '12px' elsewhere.

Safari returns null for any non-inline property if the element is hidden (has display set to 'none').

Caveats

Early versions of Prototype attempted to "fix" this behavior for certain properties. A few examples:

  1. Reading and writing the CSS opacity property works exactly like calling Element.getOpacity and Element.setOpacity respectively. This lets us pretend that IE didn't have a proprietary way to set opacity in versions 6-7.
  2. Browsers disagree on how to report certain properties of hidden elements (i.e., display: none). Opera, for instance, says that a hidden element has a width of 0px. It's an arguable point, but we return null in those cases instead (so as to agree with the majority behavior). In short: if an element is hidden, getStyle('width') and getStyle('height') will return null.
  3. In older versions of Internet Explorer, Prototype will return a pixel value for width and height, even if the literal value is a different unit. It does this by treating width like offsetWidth and height like offsetHeight. This is often the incorrect measurement, but it's a mistake we're stuck with for backward-compatibility. If you're trying to measure an element's dimensions, don't use getStyle; use Element.measure instead.

This method can be called either as an instance method or as a generic method. If calling as a generic, pass the instance in as the first argument.