You may have noticed a strange 4px gap in between images or other elements. You may have also tried to “margin: 0; padding: 0;
“ it out; without success. Here is all you need to know about this phenomenon.
The Explanation
Example
Let’s set the stage and observe the problem:
<div> |
See the Pen PGwRxg by Jonathan klughertz (@klugjo) on CodePen.
As you can see in the code pen, the dreaded 4px gap is there.
Here is why
The key to understanding what is going on is being aware of two things:
<img />
element behave likedisplay: inline-block;
by default.inline-block
behave like words in a sentence. That means that they are separated by white spaces.
There are no margins or paddings, the gaps are simple whitespaces, just like in between the words of this sentence.
It is the same as in :
<span>Snoop</span> <span>Dog</span> |
You would expect your browser to separate the words Snoop and Dog with a space. The same thing happens with images, they are separated with a whitespace.
Note that this will happen with all display: inline-block
elements.
Fixes
There are a few fixes you can apply if you want to get rid of that whitespace.
Put the HTML in one line
If you can, put all your HTML elements in one line, so as to remove the line breaks (interpreted as white spaces)
<div> |
See the Pen gwbZEy by Jonathan klughertz (@klugjo) on CodePen.
Set the parent’s font-size to 0
You can set the parent container to font-size: 0
. The white space in between the images will then be 0.
<div class="container"> |
And in your CSS:
.container { |
See the Pen GjgxLL by Jonathan klughertz (@klugjo) on CodePen.
Fight the gap with a negative margin
This is another solution that does not force you to modify your HTML markup.
.container img { |
See the Pen Kgwojr by Jonathan klughertz (@klugjo) on CodePen.
Use float: left;
One last solution would be to set the images to display: block
, then place them horizontally using float: left;
.
.container img { |
See the Pen VKYXJE by Jonathan klughertz (@klugjo) on CodePen.
There you go. I hope I was able to shine some light on this matter. Filling in that gap should now be a walk in the park.