MDN may have intermittent access issues April 18 13:00 - April 19 01:00 UTC. See whistlepig.mozilla.org for all notifications.

mozilla
Your Search Results

    HTMLElement.style

    Summary

    The HTMLElement.style property returns a CSSStyleDeclaration object that represents the element's style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.

    Setting style

    Since the style property has the same (and highest) priority in the CSS cascade as an inline style declaration via the style attribute, it is useful for setting style on one specific element.

    It is generally better to use the style property than to use elt.setAttribute('style', '...'), since using the style property will not overwrite other CSS properties that may be specified in the style attribute.

    Except in Opera, styles can not be set by assigning a string to the (read only) style property, as in elt.style = "color: blue;". This is because the style attribute returns a  CSSStyleDeclaration object. Instead, you can set style properties like this:

    elt.style.color = "blue";  // Directly
    
    var st = elt.style;
    st.color = "blue";  // Indirectly

    Getting style information

    The style property is not useful for learning about the element's style in general, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the <head> section, or external style sheets. To get the values of all CSS properties for an element you should use window.getComputedStyle() instead.

    Example

    var div = document.getElementById("div1");
    div.style.marginTop = ".25in";

    The following code displays the names of all the style properties, the values set explicitly for element elt and the inherited 'computed' values:

    var elt = document.getElementById("elementIdHere");
    var out = "";
    var st = elt.style;
    var cs = window.getComputedStyle(elt, null);
    for (x in st) {
      out += "  " + x + " = '" + st[x] + "' > '" + cs[x] + "'\n";
    }

    Specification

    DOM Level 2 Style: ElementCSSInlineStyle.style

    Compatibility

    Note: Starting in Gecko 2.0, you can set SVG properties' values using the same shorthand syntax. For example:

    element.style.fill = 'lime';

    See also

    Hide Sidebar