user965369
user965369

Reputation: 5743

Width of a DIV is nothing according to Javascript, why?

DIV's width is nothing according to DOM's Javascript.

This is such a simple little problem, but its well annoying.

<html>
    <head>
        <style>
            div#foot_wrapper{
                width:650px;
                height:20px;
                position:absolute;
                bottom:10px;
                background-color:#000000;
            }
        </style>
        <script>

            function align(div){
                                 alert(div.style.width); // ---------------- box pops up blank?
                div.style.left = (window.innerWidth/2) - (div.style.width/2);       
            }
        </script>

    </head>

    <body onload="align(document.getElementById('foot_wrapper'))" onresize="align(document.getElementById('foot_wrapper'))" >

        <div id="main">
        </div>

        <div id="foot_wrapper">
        </div>

    </body>
</html>

Upvotes: 3

Views: 589

Answers (3)

kapa
kapa

Reputation: 78751

Try div.offsetWidth MDN instead of div.style.width.

The style MDN property only reflects the styles that were set inline on an element (using the style attribute on the element).

See also Javascript - Get Style Quirksmode

(For the best results you could use a library like jQuery. The authors have already worked around the possible browser differences and quirks, so you won't have to deal with those.)

Upvotes: 7

duri
duri

Reputation: 15351

This is because style DOM attribute contains only CSS properties defined inline. If you'd use <div style="width: 650px;">, you'd see correct result. For dimensions, use innerWidth/clientWidth, other properties can be read using window.getComputedStyle() (modern browsers) or currentStyle DOM attribute (IE<=8). Both behave a bit differently - if you use width: 1em, getComputedStyle returns 16px and currentStyle returns 1em, but it should be enough for some simpler tasks.

Upvotes: 0

Guffa
Guffa

Reputation: 700840

The style property gives you the style assigned directly to the element, not the styles that are applied from a style sheet, or inherited.

Upvotes: 2

Related Questions