CSS - 如果子项为空则隐藏元素[重复]

问题描述 投票:0回答:2

如果子元素为空,是否可以隐藏父元素?我知道有

:empty
选择器,但它仅在父级不包含任何内容(包括 HTML 元素)时才有效。

这是我的 HTML:

<div class="row">
    <div class="center">
        <span class="text-danger label-promotion"><strong></strong></span>
    </div>
</div>

还有我的 CSS,遗憾的是它不能以这种方式工作,但我想你明白我想要做什么:

.label-promotion:empty {
    display: none;
}

如果为空,我希望

<span>
不出现,我想为此避免使用JS。这可能吗?

html css
2个回答
11
投票

您可以使用 has()(Firefox 尚不支持):

.label-promotion:has(> strong:empty) {
    display: none;
}

如果

.label-promotion
的孩子永远是
<strong>
,你可以这样做:

.label-promotion strong:empty {
    display: none;
}

隐藏

<strong>
。但是,您无法使用 CSS 隐藏
<span>
本身。 请参阅类似问题的答案:如果内部 div 为空,我想隐藏我的外部 div


2
投票

为此我想避免使用 JS

是的,我同意,拥有纯 CSS 解决方案总是更好。

但在这种情况下,您需要做的就是:

  • 找到所有
    .label-promotion
    <spans>
  • 遍历它们,检查每个是否有空
    <strong>
  • 如果是,添加到
    <span>
    班级
    .is-empty

工作示例:

// Find all the .label-promotion <spans>
const labelPromotions = document.querySelectorAll('.label-promotion');

// Loop through them... 
for (labelPromotion of labelPromotions) {

  let strong = labelPromotion.getElementsByTagName('strong')[0];
  
  // ... checking if each has an empty <strong> 
  if (strong.textContent === '') {
    
    // If it does, add to to the <span> the class .is-empty
    labelPromotion.classList.add('is-empty');
  }
}
span {
  display: inline-block;
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border: 1px solid rgb(255, 0, 0);
  vertical-align: middle;
}

.is-empty {
  display: none;
}
<span class="text-danger label-promotion"><strong>A</strong></span>
<span class="text-danger label-promotion"><strong></strong></span>
<span class="text-danger label-promotion"><strong>C</strong></span>
<span class="text-danger label-promotion"><strong>D</strong></span>
<span class="text-danger label-promotion"><strong></strong></span>
<span class="text-danger label-promotion"><strong></strong></span>
<span class="text-danger label-promotion"><strong>G</strong></span>

© www.soinside.com 2019 - 2024. All rights reserved.