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

Mia*_*Mia 2 html css html5 css3

是否可以创建一个条件div显示取决于是否存在另一个div的内容?我正在寻找一个只有CSS的解决方案.

我以前用过这样的东西:

.myClass:empty:before {
    content: 'content added to empty div';
}
Run Code Online (Sandbox Code Playgroud)
  • 将内容添加到空div.但由于无法在创建的伪内容中创建超链接,我正在寻找另一种方式.

所以让我们假设我的div结构如下:

<div class="div1"></div>
<div class="div2">This should be displayed</div>
Run Code Online (Sandbox Code Playgroud)

如果div1为空,是否可以执行css技巧来显示div2; 但如果div1有内容,请隐藏它?

随意重构div层次结构,我正在寻找的不依赖于当前的div结构.

寻找想法.谢谢.

Dav*_*mas 7

我建议:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)

/* 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


小智 5

使用css- next element selecor

.div1:empty + div{
    content: 'content added to empty div';
}
Run Code Online (Sandbox Code Playgroud)