Leveraging the power of Grid to stack elements on top of one another

Is there a way to achieve the same layering effect as using absolute positioning with div elements one, two, and three, while always displaying div.main, by utilizing CSS grid?

  • div.main is always visible
  • div one, two, three will appear when necessary

Update: A toggle button has been added for better visualization

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 class="content">
  <div class="main on">This is main</div>
  <div class="one">This is one</div>
  <div class="two">This is two</div>
  <div class="three">This is three</div>
</div>

Answer №1

If you want the div elements to simply stack on top of each other, one way to achieve this is by setting the content as a grid with a single cell, and then placing all the div elements in that cell using grid-area: 1/1/1/1.

Here's an example with a basic display toggle functionality:

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++;
});
.container {
  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 class="container">
  <div class="main">This is main</div>
  <div class="one">This is one</div>
  <div class="two">This is two.</div>
  <div class="three">This is three.</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What might be causing the in-viewport javascript to not work in my code?

Why is my in-viewport JavaScript code not functioning properly? Link to JSFiddle code When the Click to move button is clicked, the cat image will slide correctly. However, when implementing the following code: if($("#testtest").is(":in-viewport")) ...

The issue of height and width always being zero in Chrome when using Classic ASP with JavaScript

Within my markup, I have an image field that I am setting the source for using JavaScript. I am in need of its height and width, so I utilized the image.height() and image.width() methods. Despite working properly in Internet Explorer, these methods do not ...

Responsive Bootstrap navigation bar with a prominent logo

I am currently working on creating a navigation bar with logo following two different layouts. The first layout should be centered vertically and look like this on desktop: Desktop Layout For mobile devices, the layout should resemble this design: Mobile ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

Creating a mask overlay that covers the entire screen while excluding a specific sibling div

My goal is to create a div that acts as a mask covering the entire window. It should have an opacity of 0.5 and a background color of lightgray. However, there is one particular div on the screen that I do not want to be affected by the mask. I attempted t ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

Align a flex item at the center of its parent when the parent has a flex direction of column

My challenge is aligning a flex item vertically within the remaining space allocated to it. This is my current code snippet: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e0e ...

Checkbox and Ionic avatar image combined in a single line

I am currently working on a mobile app using the ionic framework. I would like to create a layout with an avatar image on the left, text in the middle, and a checkbox on the right. Can anyone provide guidance on how to achieve this? The code snippet below ...

Guide to creating scrolling parallax web page effects with JavaScript

I am new to Javascript and recently came across a website with a fascinating scroll parallax effect. The images on the site overlap and move as you scroll, similar to the effect on this particular website Example website: let scrollH; let photo1 = do ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

Tips for folding the center div downwards

In the code snippet below, there are three divs that should respond to window resizing by adjusting their layout. When the window becomes too small, the middle div should move down as illustrated in the accompanying image. <!DOCTYPE html> <html&g ...

What is the best way to position my header at the top of my navigation bar?

I am new to the world of HTML and CSS! My goal is as follows: https://i.stack.imgur.com/hmLNS.png This is my progress so far: https://i.stack.imgur.com/rav8P.png I am also looking to have the header fill the entire browser window and remain fixed, wit ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

${IDHERE} element's text color not changing when tab is switched

One dilemma I encountered involves displaying a percentage on a webpage with 2 tabs. The percentage is originally shown on the tab that is open when the page loads. The JavaScript code I used is quite straightforward: adaPercentColor(percent, ada) { ...

How about trying out the magic of Bootstrap columns?

My issue pertains to bootstrap columns. Whenever I zoom in on the browser, the columns start overlapping and the text from col-md-7 ends up over the image. Does anyone know of a solution to this problem? <div class="row"> <div class="col-md-5 ...

What is the best way to elegantly finish a live CSS animation when hovering?

Currently, I am working on a planet orbit code where I want to enhance the animation speed upon hover. The goal is for the animation to complete one final cycle at the new speed and then come to a stop. I have been successful in increasing the speed on hov ...

Adjusting Column Placement in Bootstrap Grid System

I am struggling to achieve a specific bootstrap grid system and could use some guidance. Here is the grid system I am trying to create: https://i.sstatic.net/fhEHU.jpg I have attempted to implement the grid system using the code provided in this JSFiddl ...

Retrieve PHP variable from a PHP CSS file

I'm facing an issue where I am unable to retrieve a PHP variable from a CSS file that is loaded in this manner from my index.php: <link href="css/style.php" rel="stylesheet"> Within the style.php file, the code looks like this: <?php heade ...

Using Flexbox to ensure two elements do not appear next to each other

When viewing on large screens, I want all elements to be on one row. On smaller screens, I want them to be on three rows. Specifically, I don't want to see the button next to the H1 element on the same row. How can flexbox help solve this problem? Tha ...

Ways to emphasize a specific row within a table for special occasions

I have limited knowledge of CSS and JavaScript, but I am looking for a way to create a notification highlight that functions similarly to when someone comments on a Facebook post. When clicked, it should direct me to the specific comment with a temporary h ...