I have a set of <span>
elements (each of them is nested to correspondent <div>
). They build a stack of panels, like in the picture below.
When span contains some text, it has a normal height. But when it is empty, it's height is 0px. But I need it to have a normal height (to make it look like in the picture).
How to achive this behavior? (I tried to insert a space, but maybe there's a better solution).
The <span> tag is a inline element, it fits into the flow of the content and can be distributed over multiple lines. We can not specify a height or width or surround it with a margin. It can be placed inside a paragraph to define a part of it without affecting the appearance of the text.
Here is a simple and robust solution:
span.item:empty:before { content: "\200b"; // unicode zero width space character }
(Update 12/18/2015: rather than using \00a0
non-breaking space, use \200b
, which is also a non-breaking space, but with zero width. See my other answer at https://stackoverflow.com/a/29355130/516910)
This CSS selector only selects the spans that are "empty", and injects some content into that empty space, namely a non-breaking space character. So no matter what font size and line-height you have set, everything around that <span>
will fall into line, just as if you had text present in that <span>
, which is probably what you want.
http://plnkr.co/edit/eXHphA?p=preview
The result looks like this:
I see two problems with using min-height
:
Here's what the counter-examples look like when things go wrong:
http://plnkr.co/edit/zeEvca?p=preview
http://plnkr.co/edit/GGd7mz?p=preview
Code for this last example:
<div class="group"> Hello <span class="item">Text</span> </div> <div class="group"> Huh? <span class="item"></span> </div> <div class="group"> Yes! <span class="correct"></span> </div>
css:
.group { background-color: #f1f1f1; padding: 5px; font-size: 20px; margin-bottom: 20px; } .item { background-color: #d2e3c5; border-radius: 6px; padding: 10px; margin-bottom:5px; display: inline-block; min-height: 20px; } .correct { background-color: #d2e3c5; border-radius: 6px; padding: 10px; margin-bottom:5px; display: inline-block; } .correct:empty:before { content: "\00a0"; }
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