Do not display empty inline-block elements with CSS

I have this HTML layout:

<p>foo</p><p>bar</p>
<p>foo2</p><p>bar2</p>
<p></p><p></p>
<p>foo4</p><p>bar4</p>
<p></p><p></p>

which is styled as:

p{display:inline-block; width:50%;margin:0;}
p:nth-child(even){text-align:left;background:red;}
p:nth-child(odd){text-align:right;background:blue;}

The problem is that empty elements take space. Is it possible (only with CSS) to prevent the empty elements from take up vertical space?

Here is a fiddle of the problem


solution

Use the :empty pseudo class to hide the empty elements:

Example Here

p:empty {
  display: none;
}
p {
  display: inline-block;
  width: 50%;
  margin: 0;
}
p:nth-child(even) {
  text-align: left;
  background: red;
}

p:nth-child(odd) {
  text-align: right;
  background: blue;
}
p:empty {
  display: none;
}
<p>foo</p><p>bar</p>
<p>foo2</p><p>bar2</p>
<p></p><p></p>
<p>foo4</p><p>bar4</p>
<p></p><p></p>