How to layer multiple elements on top of one another?

<div class="parent">
  <div class="child" id="child-A">
  <div class="child" id="child-B">
  <div class="child" id="child-C">
</ div>

So the idea is that initially, child-A will be on top, meaning child-B and child-C won't be visible because they will be on the bottom, covered / shielded by child-A.

So there will be a toggle that shrinks the width of each child to set who is visible and who is hidden.

Upvotes: 0

Views: 483

Answers (2)

Saeed Shamloo
Saeed Shamloo

Reputation: 6564

You can acheive your goal by using css position and z-index, and in order to toggle the active on, you can mutate item's class by JS. Here is an simple example, by clicking on the black area, the active on will be change.

let i = 0;
const children = document.querySelectorAll('.child');

function toggleDiv() {
  children[i].classList.remove('active');
  i = (i + 1) % 3; //since we have 3 child
  children[i].classList.add('active');
}
.child {
  position: absolute;
  height: 100px;
  width: 100px;
  font-size: 20px;
  background: black;
  color: white;
}

.child.active {
  z-index: 1;
}
<div class="parent" onClick="toggleDiv()">
  <div class="child active" id="child-A">child-A</div>
  <div class="child" id="child-B">child-B</div>
  <div class="child" id="child-C">child-C</div>
</div>

Upvotes: 1

Himanshu Saini
Himanshu Saini

Reputation: 812

const checkboxes = document.querySelectorAll( 'input[type=checkbox]' );

var myFunction = function( event ) {
    var attribute = event.target.getAttribute("data-target");
    var element = document.getElementById(attribute);
    if (element.style.display === "none")
    element.style.display = "block";
    else 
    element.style.display = "none";
};

for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', myFunction, false);
}
.child{
width:200px;
height:200px;
position:absolute;
}

#child-A{
background:red;
z-index:100;
}

#child-B{
background:blue;
z-index:99;
}

#child-C{
background:yellow;
z-index:98;
}

#controls{
margin-left: 210px;
}
<div class="parent">
  <div class="child" id="child-A"></div>
  <div class="child" id="child-B"></div>
  <div class="child" id="child-C"></div>
</div>

<div id="controls">
<label><input type="checkbox" data-target="child-A" checked/> Child A </label> <br>
<label><input type="checkbox" data-target="child-B" checked/> Child B </label> <br>
<label><input type="checkbox" data-target="child-C" checked/> Child C </label> <br>
</div>

Upvotes: 1

Related Questions