Unable to set z-index via CSS

<html>
<head>
    <title>Sample</title>

    <script>
        window.onload = function()
        {
            alert(document.getElementById('div1').style.zIndex);
            alert(document.getElementById('div2').style.zIndex);
        }
    </script>

    <style type="text/css" media="screen">
        #div2
        {
            z-index: 1;
        }
    </style>
</head>
<body>
    <div id="div1" style="z-index:1"></div>
    <div id="div2"></div>
</body>

The result of the above code is “1” for the first warning, and nothing for the second.

Why can't I set the z-index from div2 via CSS?

Thank.

+3
source share
3 answers

1: it is installed, but JS cannot determine it if it is not installed in line 2: it will have no effect if the object is not located (as indicated by gulbrandr)

regarding 1. If it is not installed inline (or javascript), you can get it using currentStyle or getComputedStyle , which gives you the currently applied style.

+3
source

W3Schools.com:

z-index (: , : : )

+2

The property set .style.*directly refers to the properties set using the attributestyle , not those that are cascaded from the corresponding stylesheet.

To find the computed z-index you need to use getComputedStyle

+1
source

Source: https://habr.com/ru/post/1775838/


All Articles