I am using absolute positioning to layer div
one
, two
, three
(and cover main
). Would it be possible to achieve the same with CSS grid?
div.main
is always displayeddiv
one
,two
,three
will be shown when needed
Update: Toggle button added for better visualisation
const div = document.querySelector('div.content');
document.querySelector('button').addEventListener('click', () => {
const on = document.querySelector('.on');
on?.classList.remove('on');
(on?.nextElementSibling || div.firstElementChild).classList.add('on');
});
* {
box-sizing: border-box;
}
button {
padding: 0.5em;
margin-bottom: 1em;
}
.content {
width: 15em;
height: 8em;
position: relative;
margin: 0;
padding: 0;
border: 1px solid #aaa;
}
.main {
height: 100%;
background: #eee;
padding: 0.5em;
}
.one,
.two,
.three {
display: none;
margin: 0;
padding: 2em;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 3;
}
.one.on,
.two.on,
.three.on {
display: block;
}
.one {
background: #fef8;
}
.two {
background: #fec8;
}
.three {
background: #cdc8;
}
<button>Toggle</button>
<div >
<div >This is main</div>
<div >This is one</div>
<div >This is two</div>
<div >This is three</div>
</div>
CodePudding user response:
Assuming that the div
just need to stack on each other, perhaps a simple implement would be setting content
a grid of a single cell, and have all the div
placed in grid-area: 1/1/1/1
.
Example: (with a simple display toggle)
const btn = document.querySelector("button");
const divs = document.querySelectorAll("div > div");
let i = 1;
btn.addEventListener("click", () => {
if (i === 4) {
divs.forEach((div) => div.classList.remove("on"));
i = 1;
return;
}
divs[i - 1].classList.toggle("on");
divs[i].classList.toggle("on");
i ;
});
.content {
width: 15em;
height: 20em;
margin: 0;
padding: 0;
border: 1px solid blue;
display: grid;
}
.main {
border: 1px solid red;
grid-area: 1/1/1/1;
}
.one,
.two,
.three {
display: none;
margin: 0;
padding: 1em;
z-index: 3;
border: 1px solid green;
grid-area: 1/1/1/1;
}
.one.on,
.two.on,
.three.on {
display: block;
}
button {
padding: 6px;
margin-bottom: 1em;
}
.one {
background-color: rgba(100, 149, 237, 0.25);
}
.two {
background-color: rgba(34, 139, 34, 0.25);
}
.three {
background-color: rgba(255, 140, 0, 0.25);
}
<button>Toggle</button>
<div >
<div >This is main</div>
<div >This is one</div>
<div >This is two.</div>
<div >This is three.</div>
</div>