CSS - 如果 div 元素为空,显示内容

6

有没有可能根据另一个div是否存在来创建条件性的div显示?我正在寻找一种纯CSS的解决方案。

我之前使用过类似于以下内容的东西:

.myClass:empty:before {
    content: 'content added to empty div';
}
  • 要向空的 div 添加内容。但由于无法在创建的伪内容中创建超链接,因此我正在寻找另一种方法。

因此,假设我的 div 结构如下:

<div class="div1"></div>
<div class="div2">This should be displayed</div>

如果div1为空,可以使用CSS技巧显示div2吗?但是如果div1有内容,则隐藏它?

可以自由地重构div层次结构,我所寻找的并不取决于当前的div结构。

希望能得到一些想法。谢谢。

3个回答

8
我建议:
/* hiding the div.div2 element (and its content)
   if it's the next element-sibling of div.div1: */
div.div1 + div.div2 {
    display: none;
}

/* selecting the div.div2 element which is the next
   element-sibling of an empty (div.div1:empty)
   div.div1 element: */
div.div1:empty + div.div2 {
    display: block;
}

/* hiding the div.div2 element (and its content)
       if it's the next element-sibling of div.div1: */
div.div1 + div.div2 {
  display: none;
}

/* selecting the div.div2 element which is the next
       element-sibling of an empty (div.div1:empty)
       div.div1 element: */

div.div1:empty + div.div2 {
  display: block;
}

div.div1 {
  border: 1px solid #f00;
  color: #f00;
}

div.div2 {
  color: #0f0;
  border: 1px solid #0f0;
  margin-bottom: 1em;
}
<div class="div1"></div>
<div class="div2">This should be displayed</div>

<div class="div1">This is 'div.div1' (it has content)</div>
<div class="div2">This should not be displayed</div>


6

使用 CSS-next 元素选择器。

.div1:empty + div{
    content: 'content added to empty div';
}

1
由于在创建的伪内容中无法创建超链接,我正在寻找另一种方法。 - JDB
1
哦,是的,但“+”可能会起到将次要元素显示为块级元素的作用! - Mia

1

感谢您的快速答复。根据Alexis Peters的回答,我创建了这个可以完美运行的代码。下面是代码,以备将来参考:

div2 {
    display: none;
}

.div1:empty + .div2{
    display: block;
}

对于像我这样的探险家,上面的CSS解释是“将div2设置为不显示。如果任何一个空的div1后面跟着一个div2,则将其显示为块级元素”。

干杯。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接