I have the following problem: I am creating an inline-block element (.content) within a wrapper-div (.wrapper). If there is content in the .content-div, everything works just fine. But if I remove the content from the .content-div, a space gets added below the inline-block-div.
I am not sure why this happens and how to fix it correctly. Note that after manually removing all spaces and line-breaks in my code the problem persists, but setting the font-size to 0 helps.
Also, setting vertical-align: top to the .content-div helps. I am not sure why exactly.
Whats the best way of fixing it? Why does this happen?
Fiddle: https://jsfiddle.net/cjqvcvL3/1/
<p>Works fine:</p>
<div class="wrapper">
<div class="content">not empty</div>
</div>
<p>Not so much:</p>
<div class="wrapper">
<div class="content"></div>
</div>
.wrapper {
background-color: red;
margin-bottom: 20px;
/* font-size: 0; *//* this would fix it, but why? (problem persists after manually removing all spaces and breaks) */
}
.content {
display: inline-block;
height: 20px;
width: 200px;
background-color: green;
/* vertical-align: top; *//* this would fix it, but why? */
}
Update
I have put together a new fiddle. This should better illustrate my problem. How do I get rid of the green line below the textarea?
https://jsfiddle.net/cjqvcvL3/7/
<div class="content"><textarea>Some Content</textarea></div>
.content {
display: inline-block;
background-color: green;
}
The inline-block display property treats block level elements (e.g. <div> ) as an inline element (e.g. <span> ), and, just like if you had a line break between two <span> elements, the line-break between the <div> s is creating a space between the <div> s. That extra margin is actually a space—not a margin.
You get whitespace there because you have whitespace inbetween the divs. Whitespace between inline elements is interpreted as a space. However, this is a bad way to do what you want to do. You should float the elements if thats what you want to do.
apply float:left and that will remove the space so the text doesn't have to be on 1 line.
This happens because you specifically give width and height to the .content
.
Have you considered using the :empty
pseudo selector?
.content:empty {
display: none;
}
https://jsfiddle.net/cjqvcvL3/5/
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