Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the inherited CSS value using Javascript?

I'm trying to get the value of an inherited CSS property using Javascript. I haven't been able to find a comprehensive answer.

Example CSS:

div {
    width: 80%;
}

Example Markup:

<div id="mydiv"> Some text </div>

Using javascript (jQuery, or native), I need to get the width of the element-- not in pixels, but the string "80%".

$('#mydiv').css('width'); // returns in px
$('#mydiv')[0].style.width // empty string
getComputedStyle($('#mydiv')[0]).width // returns in px

The reason I need the value as a string is because I need to copy the style to another element. If it's declared as a percent, the other value needs to be a percent. If it's declared in px, the other value needs to be in px.

The real trick is that this property could be inherited, not declared explicitly on the element (as in my example).

Does anyone have any ideas?

like image 930
t3rminus Avatar asked Mar 15 '12 23:03

t3rminus


People also ask

How do you retrieve a CSS property value of an element?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

How do you inherit CSS styles?

The inherit CSS keyword causes the element to take the computed value of the property from its parent element. It can be applied to any CSS property, including the CSS shorthand property all . For inherited properties, this reinforces the default behavior, and is only needed to override another rule.

Can I use inherit CSS?

The inherit keyword specifies that a property should inherit its value from its parent element. The inherit keyword can be used for any CSS property, and on any HTML element.


1 Answers

What you are searching for is this quirksmode.org article. It proposes the function

function getStyle(el, styleProp)    {
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

Still, you should read that article carefully. They names of the styleProps are not really cross-browser, and you will see how different browsers handle this. Opera seems to have the best support for reporting the correct values.

like image 145
Bergi Avatar answered Oct 29 '22 03:10

Bergi