Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove space below empty inline-block div (and why is it there anyway?)

Tags:

html

css

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&#13;&#10;Content</textarea></div>

.content {
  display: inline-block;
  background-color: green;
}
like image 487
user2482138 Avatar asked Oct 19 '22 15:10

user2482138


People also ask

Why inline block has space?

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.

Why is there white space between divs?

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.

How do I remove unnecessary space in CSS?

apply float:left and that will remove the space so the text doesn't have to be on 1 line.


1 Answers

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/

like image 198
Jonas Grumann Avatar answered Oct 26 '22 23:10

Jonas Grumann