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

Saving fonts when deploying on Vercel with Next.js is not supported

Troubleshooting Differences in Local Viewing and Deployment: https://i.stack.imgur.com/jktPN.png When viewing locally, everything appears as expected. However, upon deploying, there are noticeable discrepancies. https://i.stack.imgur.com/NKQQ6.png Even ...

Dynamically insert textboxes into a form by leveraging the power of the Jade template engine

Looking for a solution to a simple requirement that doesn't seem to have a clear answer online. I need a combobox on my jade page that accepts numbers as input. When the user selects a number, I want the page to refresh and display that many textboxes ...

Setting up SKPM (Sketch Plugin Manager) using npm

I've been trying to install a specific npm package, but I keep encountering numerous errors that are unfamiliar to me. It's important to note that these errors occur after running the command sudo npm install -g skpm: gyp ERR! configure error g ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

What is the best way to populate a dropdown menu by matching keys from an array within an ng-repeat

My JSON structure looks like this: 101 : "List": [ { "Name": "Pink" }, { "Name": "Black" } ] 102 : "List": [ { "Name": "Red" }, { "Name": "Yellow" } ] $sco ...

What is the process for setting up custom HTML tags in Resharper?

I am looking to customize my HTML files by using custom tags to incorporate knockout components [1]: <like-widget params="value: userRating"></like-widget> To enable the tag in VisualStudio's HTML formatting settings, I made the followin ...

Attempting to implement image switching with hover effects and clickable regions

Hey there, I'm currently working on a fun little project and could use some guidance on how to achieve a specific effect. The website in question is [redacted], and you can view the code I've used so far at [redacted]. You'll find a code blo ...

Tips for implementing a search function with DynamoDB using the "contains" operator

I'm currently working on implementing a search function in my React application. Here is the structure of my DynamoDB table: --------------------- movie_id | movie_name --------------------- 1 | name a --------------------- 2 | name b ...

Adjust the alignment of two headers with varying sizes

Can someone provide guidance on aligning two headers of different sizes (e.g. h3 and h5) based on their bottom edges, making them appear like a cohesive group in a sentence format? The current code snippet I am working with is as follows: ...

What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

What is the best way to verify the existence of an email address?

I'm currently using the jQuery validation plugin and everything is working fine, but I've hit a snag when it comes to checking email addresses. The issue is that the plugin returns either true or false based on whether the email exists or not. Ho ...

Problem with parsing JSON in a mixed array

When making a YouTube API call, the response includes a var result = JSON.stringify(response, '', 2); that has the following structure: { "kind": "youtube#searchListResponse", "pageInfo": { "totalResults": 1000000, ...

Successive pressing actions

I am struggling to grasp a unique Javascript event scenario. To see an example of this, please visit http://jsfiddle.net/UFL7X/ Upon clicking the yellow box for the first time, I expected only the first click event handler to be called and turn the large ...

Control your thumbnails with the powerful iDangerous Swiper feature

Are you new to coding? I'm looking for help on linking thumbnail images to a swiper so that when a thumbnail is clicked, it moves the swiper-container to the corresponding slide. Any ideas or suggestions would be greatly appreciated! Here's an e ...

The graphic is displayed at a width of 50%

I am currently working on a FrontEnd project and implementing Bootstrap 3 for the grid system. Additionally, I am utilizing art direction with the picture element. However, I seem to be facing an issue with the images. Every time I include the following s ...

The Script Component is not functioning properly in next.js

While using Tiny Editor, I encountered an issue with defining a key for the editor. According to the documentation, I need to access this key through the tag <script src='address'. This method seems to work fine initially. However, when combin ...