You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS技术难题:如何基于DOM结构与可见元素双条件隐藏子元素

解决方案

要实现你描述的需求,仅通过CSS可以借助:has()伪类来实现,核心是判断可见元素的总数以及目标子元素的DOM位置。假设父元素类名为.parent,子元素为其直接子节点,具体代码如下:

/* 当DOM最后一个子元素处于奇数位,且可见元素总数为奇数时,隐藏该最后一个子元素 */
.parent:has(:last-child:not(.display-none):nth-child(odd)):has(:not(.display-none):nth-last-child(1):nth-child(odd)) :last-child:not(.display-none) {
  display: none;
}

代码说明:

  • .parent:has(:last-child:not(.display-none):nth-child(odd)):筛选出最后一个子元素可见,且该子元素在DOM结构中处于奇数位置的父元素。
  • :has(:not(.display-none):nth-last-child(1):nth-child(odd)):进一步确认可见元素总数为奇数——因为最后一个可见元素是奇数位,且无后续可见元素,说明总数为奇数。
  • 最终选中符合条件的最后一个可见子元素,设置display: none完成隐藏。

补充优化:

如果你的核心需求是让可见元素始终保持偶数个,可以简化规则为直接隐藏总数为奇数时的最后一个可见元素:

.parent:has(:not(.display-none):nth-last-child(1):nth-child(odd)) :not(.display-none):last-child {
  display: none;
}

注意::has()伪类仅在Chrome 105+、Safari 15.4+等现代浏览器中支持,若需兼容旧浏览器,需结合JavaScript计算可见元素数量来控制显示。

内容的提问来源于stack exchange,提问作者turik97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:05:00