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
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With