Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 353
Ormoz Avatar asked Jun 17 '26 23:06

Ormoz


2 Answers

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>
like image 141
Josh Crozier Avatar answered Jun 19 '26 14:06

Josh Crozier


You can use the :empty pseudo-class to select and hide those elements.

But you have to be careful while using this pseudo-class selector because this won't work even if the element has a single space inside.

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>

The below snippet is just to show how it doesn't select elements that aren't completely empty (devoid of spaces).

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>
like image 38
Harry Avatar answered Jun 19 '26 12:06

Harry