Why does my getComputedStyle console.logs initial values

128 views Asked by At

I wanted to use getComputedStyle to access css properties, unfortunately it only console.log()'s standard properties.

Below you will find my code.

On the picture you will find what it logs.

logs


<body>
    <div id="box">box</div>


    <script>
        const box = document.getElementById("box");
        
        const boxCS = window.getComputedStyle(box)
        
        console.log(boxCS.zIndex)
        </script>
</body>

<style>
    #box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    position: absolute;
    z-index: 1;
    background-color: rgb(200, 200, 200);
}
</style>
2

There are 2 answers

1
Animus On BEST ANSWER

One of the reasons is that you declare styles after the script. If you put it before script, it'll be okay. Example

0
idleberg On

Your script is running before the rendering of the DOM is complete. Try wrapping your preset in an event-listener. That way it's irrelevant in which order scripts and styles are inlined or loaded externally.

Example

window.addEventListener("DOMContentLoaded", () => {
    const boxElement = document.getElementById("box");
    const boxStyle = window.getComputedStyle(boxElement)
        
    console.log(boxStyle.zIndex)
});

Refer to the MDN documentation on DOMContentLoaded for details.