Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But what if we need to reverse this order for specific children within a container?

For example, imagine having multiple overlapping floated divs within a parent div:

__________________________________
|  _________________________      |
|  | samant| allis| rachael |...  |
|  |_______|______|_________|...  |
|_________________________________|

And we actually want it to be displayed like this:

__________________________________
|  _________________________      |
|  | samantha | lison | chael |...  |
|  |__________|______|_______|...  |
|_________________________________|

You can view an example here.

If CSS alone does not offer a solution for achieving this effect, what would be the most efficient and secure way to implement this functionality using JavaScript for arbitrary child elements?

Similar questions have been asked before regarding reversing z-index based on page render order, such as this one and this one.

Answer №1

In order to achieve this effect in JavaScript, one approach is to select all elements using the querySelectorAll method, then iterate through them using forEach, and adjust the z-index based on the element count and current index:

var elems = document.querySelectorAll(".container2 .floater");
Array.prototype.forEach.call(elems, function(e, i) {
    e.style.zIndex = elems.length - i;
});
.container2 {
    border: 3px solid teal;
    padding: 2em;
    display:inline-block
}

.container2 .floater {
    border: 1px solid gray;
    background: #444;
    color: white;
    float: left;
    padding: 1em;
    margin: -1em;
    position: relative;
}
<div class="container2">
    <div class="floater">Item 1</div>
    <div class="floater">Item 2</div>
    <div class="floater">Item 3</div>
    <div class="floater">Item 4</div>
    <div class="floater">Item 5</div>
    <div class="floater">Item 6</div>
</div>

Answer №2

If you want to make the elements in the document tree overlap, simply reverse their order using CSS.

By utilizing techniques such as:

  • Flexible boxes:

    wrapper {
      display: flex;
      flex-direction: row-reverse; /* or `column-reverse` */
      justify-content: flex-end;
    }
    

    ul {
      display: flex;
      list-style: none;
      padding: 0 0 0 1em;
    }
    ul.reversed {
      flex-direction: row-reverse;
      justify-content: flex-end;
    }
    li {
      border: 1px solid;
      margin-left: -1em;
      background: #fff;
    }
    <ul>
      <li>Samantha</li>
      <li>Allison</li>
      <li>Rachael</li>
    </ul>
    <ul class="reversed">
      <li>Rachael</li>
      <li>Allison</li>
      <li>Samantha</li>
    </ul>

  • Floating elements:

    wrapper {
      float: left;
      clear: both;
    }
    item {
      float: right;
    }
    

    ul {
      list-style: none;
      float: left;
      clear: both;
      padding: 0 0 0 1em;
    }
    li {
      float: left;
      border: 1px solid;
      margin-left: -1em;
      background: #fff;
    }
    ul.reversed > li {
      float: right;
    }
    <ul>
      <li>Samantha</li>
      <li>Allison</li>
      <li>Rachael</li>
    </ul>
    <ul class="reversed">
      <li>Rachael</li>
      <li>Allison</li>
      <li>Samantha</li>
    </ul>

  • Direction:

    wrapper {
      direction: rtl;
      text-align: left;
    }
    item {
      direction: ltr;
    }
    

    ul {
      list-style: none;
      padding: 0 0 0 1em;
      text-align: left;
    }
    li {
      display: inline-block;
      border: 1px solid;
      margin-left: -1em;
      background: #fff;
    }
    ul.reversed {
      direction: rtl;
    }
    ul.reversed > li {
      direction: ltr;
    }
    <ul>
      <li>Samantha</li>
      <li>Allison</li>
      <li>Rachael</li>
    </ul>
    <ul class="reversed">
      <li>Rachael</li>
      <li>Allison</li>
      <li>Samantha</li>
    </ul>

Answer №3

If you're looking to mix up your layout, consider experimenting with the latest flex boxes. Try using: display: inline-flex; flex-direction: column-reverse;

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

Surprising outcomes when using Mongoose

Questioning Unusual Behavior There is a model in question: //test.js var mongoose = require('../utils/mongoose'); var schema1 = new mongoose.Schema({ name: String }) var schema2 = new mongoose.Schema({ objectsArray: [schema1] }); schema1.pre( ...

Navigating variable columns and rows in a static column table

Here is a preview of how my table will appear: <table> <thead> <tr> <th>Name</th> <th>Week 1</th> <th>Week 2</th> <th>Week 3</th> </tr> < ...

What causes the _.sum() function in lodash to not work with objects in Vuejs?

I've encountered an issue where using Vuejs and Lodash in conjunction with a computed property that calculates the sum of a property in a collection results in unexpected behavior. Instead of summing the values, it seems to concatenate the string [obj ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

Enhancing the security of various components by utilizing secure HTTP-only cookies

Throughout my previous projects involving authentication, I have frequently utilized localstorage or sessionstorage to store the JWT. When attempting to switch to httpOnly secure cookies, I encountered a challenge in separating the header component from th ...

Modify the contents of a textbox by editing the text as you type

Text within the text box follows this format: login -u username -p password When entering this text, I want to substitute 'password' with a series of '*'s equal in length. For example: 'login -u <a href="/cdn-cgi/l/email-prot ...

Send information from Node.js to the webpage and populate designated elements (search by either ID or class) on the webpage

After successfully retrieving data from the mongo database using nodejs, my goal is to display this data on a webpage. function requireUser(req, res, next){ //console.log(req.session.username); if (!req.session.username) { res.redirect('/user_un ...

What is the best way to integrate a notification system using jQuery?

I am looking to create a notification area that will refresh whenever a new message is sent using jQuery or Ajax (my database is stored in a soap server). I want to make a soap call every few seconds to achieve this, but I'm not sure how to go about i ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

What is preventing my cookie from being saved?

Whenever a user clicks "sign in", I trigger a POST ajax request. Here is the function handling that request: app.post('/auth', function(req,res,next){ var token = req.body.token ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

Converting a Class Component to a Functional Component: Step-by-Step Guide

Recently, I have been transitioning from working on class components to function components in React. However, I am facing some issues with my functional component code after converting it from a class component. In my functional component code, there is ...

Tips on including the Elastic Search JavaScript client library in Node.js controller files

Currently, I'm working on a node.js project using the express framework and creating a RESTful API. My next step is to integrate elastic search into my application. I've started by installing the elastic search JavaScript client library and addin ...

The Quirks of jQuery's .load() Method

On my website, I am incorporating a basic jQuery script to load content from one part of a webpage into the 'display container' on the same page. The content being loaded consists of multiple divs enclosed within an outer <div> that is hid ...

Troubleshooting Problems with Deploying Next Js on Firebase

I am currently working on a new Next Js application and have successfully deployed it on Vercel by linking the GitLab project. Now, I need to deploy the same project on Firebase. Here's what I have tried so far: - Ran firebase init This command gen ...

Dynamic Label Editing on ASP Page Using Master Page

I am working on an ASP page with a Masterpage element on my website. The specific functionality I am trying to implement involves having multiple labels with an edit hyperlink next to each one. When the user clicks on the Edit hyperlink, I want the label t ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

Retrieving data from a React state in one component and utilizing it in a separate component

Thank you for taking the time to assist me with this challenge. I am currently working on a project that involves creating the state goodData in one component called AddProduct and accessing it in another component named ActionBox, both within the same j ...

Is gulp.dest set to match the current file?

I'm having trouble directing my compiled .css file to the same directory as its original .scss version. gulp.task('sass', function() { return gulp.src([ appDir + '/*.scss', appDir + '/**/*. ...