Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - if div is empty, display content

Tags:

html

css

Is it possible to create a conditional div display depending on another div's content being present or not? I'm looking for a CSS only solution.

I've used something like this before:

.myClass:empty:before {
    content: 'content added to empty div';
}
  • to add content to an empty div. But since there is no way to create hyperlinks in the created pseudo-content, I'm looking for another way.

So let's assume my div structure is as follows:

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

Is it possible to do a css trick to display div2 if div1 is empty; but hide it if div1 has content?

Feel free to restructure the div hierarchy, what I'm looking for does not depend on the current div structure.

Looking for ideas. Thank you.

like image 942
Mia Avatar asked Dec 09 '22 04:12

Mia


1 Answers

I'd suggest:

/* 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>
like image 141
David Thomas Avatar answered Dec 26 '22 15:12

David Thomas