Search code examples
javascripthtmlcsspositionz-index

How to overlap one div over another div without position


In the following code, I want to div1 to overlap div2 when div1 is clicked. How do i do that without using position? And also I want to accomplish this by changing only the css of div1. Thanks in advance.

<style>
.div1
{ display:'inline-block';}
.div2
{display:'inline-block';}
enter code here
</style>
<script>
function thefunc()
{
//code to overlap div2 from div1 by only changing css of div1
}

<body>
<div id='div1' onClick={()=>thefunc()}></div>
<div id='div2'></div>
</body>

Solution

  • Consider CSS-Grid applied to the body

    function thefunc() {
      document.querySelector('body').classList.add('overlap');
    }
    #div1 {
      display: inline-block;
      background: red;
      opacity: .5;
    }
    
    #div2 {
      display: inline-block;
      background: blue;
    }
    
    div[id] {
      width: 200px;
      height: 200px;
    }
    
    .overlap {
      display: grid
    }
    
    .overlap div {
      grid-row: 1;
      grid-column: 1;
    }
    
    #div1 {
      z-index: 2;
    }
    <div id='div1' onClick="thefunc()"></div>
    <div id='div2'></div>