Search code examples
javascripthtmlcssgetcomputedstyle

Why does my getComputedStyle console.logs initial values


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>

Solution

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