Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherited CSS Values via Javascript

On my page I am changing some css styles via javascript. When I try and pull a value that has been inherited - it comes up blank. Consider the following:

    .Sliding
    {
        display: none;
        overflow: hidden;
    }

    .Sliding #FilterBox
    {
        height: 185px;
        background-color: Fuchsia;
    }

And the html:

<div class="Sliding" id="FilterBox">
        <h3>Test Form</h3>
        This is a test/<br />
        12345
</div>

If I look at the element 'document.getElementById(objname).style.display' its blank? How can I read the display value via via javascript?

like image 538
cschear Avatar asked Jul 23 '09 06:07

cschear


People also ask

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.

Do child elements inherit CSS?

The child element will naturally inherit a CSS property with its value from the parent element if the CSS property is not specified.


2 Answers

You'll want to use getComputedStyle.

The .style property is a means of accessing and setting inline style (i.e. like the style attribute).

Note, however, that your example has nothing to do with inheritance. Just rule-sets that apply directly to the elements you are interested in. Inheritance is when an element takes on the same style as its parent via the inherit keyword.

span {
    color: inherit;
}

getComputedStyle will give the final computed value though, so it will pick up inherited values too.

like image 85
Quentin Avatar answered Oct 13 '22 01:10

Quentin


Your second CSS rule:

.Sliding #FilterBox
{
    height: 185px;
    background-color: Fuchsia;
}

will match anything with id "FilterBox" that is a descendant of anything with a class "Sliding", so this rule does not apply to your div.

And to get the computed style, you can refer to Fabien's answer, or consider using jQuery, which makes this stuff a lot easier:

using jQuery, $("#FilterBox").css("display") would return the current value for "display".

like image 29
Philippe Leybaert Avatar answered Oct 13 '22 02:10

Philippe Leybaert