AndyL
AndyL

Reputation: 1655

Pure CSS Descending Z-index?

While technically I can fix my own problem with a little bit of jQuery, the question sparked my curiosity; can an unknown number of elements be z-indexed in descending order?

Here is my issue more specifically. I have an unknown number of divs that will be created by PHP in a foreach loop. The issue is that the background of these divs are (in areas) transparent and are designed to overlap. Using negative CSS margin, I can easily pull the elements to overlap one another, but the problem is that by default, css renders them with seemingly higher indices as they go down.

To illustarte what I mean, here is a fiddle.

After thinking on this for a few days, I haven't been able to come up with an answer. So, to you. Any ideas?

P.S. If anyone is coming here strictly for a jQuery solution, here it is:

$('.myClass').each(function(index) {
    zindex = index * -1;
   $(this).css('zIndex', zindex);
});

Upvotes: 1

Views: 2825

Answers (2)

Emil
Emil

Reputation: 8527

The best solution would be adding inline styles in the PHP loop.

If you know the length of the object you are looping through, you can easily calculate the inline style.

This is not the most elegant solution, but it will always work.

Upvotes: 3

robertc
robertc

Reputation: 75737

Sort of, but it's not very generic:

div:nth-last-child(1) {
    z-index: 1;
}
div:nth-last-child(2) {
    z-index: 2;
}
div:nth-last-child(3) {
    z-index: 3;
}
div:nth-last-child(4) {
    z-index: 4;
}
div:nth-last-child(5) {
    z-index: 5;
}

You could just write out hundreds of these rules, or you could generate the CSS with the same script/loop you're writing the elements out with. Or you could just include the z-index in an inline style on the element.

All in all, I think the jQuery approach is better - does it cause a functional problem for users without JavaScript enabled, or is it just aesthetic?

Upvotes: 1

Related Questions