CSS - 如果子项为空,则隐藏元素

时间:2017-03-30 15:13:50

标签: html css

如果父元素为空,是否可以隐藏父元素?我知道有:元素选择器,但它只有在父节点不包含任何东西的情况下才有效,包括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。这可能吗?

2 个答案:

答案 0 :(得分:4)

如果.label-promotion的子代始终是<strong>,则可以执行以下操作:

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

隐藏<strong>。但是,您无法使用CSS隐藏<span>本身。 请参见以下类似问题的答案:I would like to hide my outer div if inner div is empty

答案 1 :(得分:1)

我想避免使用JS

是的,我同意,最好有一个纯CSS解决方案。

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

  • 找到所有curl -v http://92.3.44.3:50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeStatus * About to connect() to 92.3.44.3 port 50070 (#0) * Trying 92.3.44.3... * Connected to 92.3.44.2 (92.3.44.2) port 50070 (#0) > GET /jmx?qry=Hadoop:service=NameNode,name=NameNodeStatus HTTP/1.1 > User-Agent: curl/7.29.0 > Host: 92.3.44.2:50070 > Accept: */* > .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;
}