【问题标题】:CSS - Hide element if child is empty [duplicate]CSS - 如果孩子为空则隐藏元素[重复]
【发布时间】:2017-08-24 14:42:11
【问题描述】:

如果子元素为空,是否可以隐藏父元素?我知道有 :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;
}

我希望&lt;span&gt; 为空时不会出现,并且我想为此避免使用 JS。这可能吗?

【问题讨论】:

  • 它不是空的,因为那里有一个&lt;strong&gt;。它必须在那里吗? (编辑)对不起,误读了问题的顶部。不,您不能根据孩子的行为影响父母。那就是 Cascading Style Sheet的 cascading 部分>
  • 您可以删除 strong 元素并为 span 元素分配一个 font-weight: bold 。这样做你可以用 span:empty { display: none; 隐藏整个跨度。 }

标签: html css


【解决方案1】:

如果.label-promotion 的孩子永远是&lt;strong&gt;,你可以这样做:

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

隐藏&lt;strong&gt;。但是,您不能使用 CSS 隐藏 &lt;span&gt; 本身。 查看类似问题的答案:I would like to hide my outer div if inner div is empty

【讨论】:

    【解决方案2】:

    我想为此避免使用 JS

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

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

    • 找到所有.label-promotion&lt;spans&gt;
    • 遍历它们,检查每个是否有一个空的&lt;strong&gt;
    • 如果有,请将.is-empty 类添加到&lt;span&gt;

    工作示例:

    // 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2014-01-13
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      相关资源
      最近更新 更多