纯 CSS 降序 Z 索引?

发布于 2024-11-19 15:04:12 字数 613 浏览 0 评论 0原文

虽然从技术上讲我可以用一点 jQuery 解决我自己的问题,但这个问题激发了我的好奇心; 可以按降序对未知数量的元素进行 z 索引吗?

这是我更具体的问题。我有未知数量的 div,它们将由 PHP 在 foreach 循环中创建。问题是这些 div 的背景(在区域中)是透明的并且被设计为重叠。使用负 CSS margin,我可以轻松地将元素拉到彼此重叠,但问题是默认情况下,CSS 在它们下降时以看似更高的索引来渲染它们。

为了说明我的意思,这里有一把小提琴。

在思考了这个问题之后几天了,我一直无法给出答案。所以,对你来说。有什么想法吗?

PS 如果有人来这里纯粹是为了 jQuery 解决方案,这里是:

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

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);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若相惜即相离 2024-11-26 15:04:12

最好的解决方案是在 PHP 循环中添加内联样式。

如果您知道要循环的对象的长度,则可以轻松计算内联样式。

这不是最优雅的解决方案,但它总是有效的。

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.

甚是思念 2024-11-26 15:04:12

有点,但它不是很通用:

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;
}

您可以写出数百条这样的规则,或者您可以使用与编写元素相同的脚本/循环来生成 CSS。或者您可以将 z-index 包含在元素的内联样式中。

总而言之,我认为 jQuery 方法更好 - 它是否会给未启用 JavaScript 的用户带来功能问题,或者只是美观?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文