Why is there an unexplainable gap between these inline-block div elements?
This question already has an answer here:
I have two inline-block
div elements, that are the same, positioned next to eachother. However there seems to be a mysterious space of 4 pixels between the two divs despite the margin being set to 0. There are no parent divs effecting them - What is going on?
This is what i want it to look like:
In this instance, your
div elements have been changed from
block level elements to
inline elements. A typical characteristic of
inline elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)
There are a few solutions that can be used to solve this.
Method 1 - Remove the whitespace from the markup
Example 1 - Comment the whitespace out: (example)
Example 2 - Remove the line breaks: (example)
Example 3 - Close part of the tag on the next line (example)
Example 4 - Close the entire tag on the next line: (example)
Method 2 - Reset the
Since the whitespace between the
inline elements is determined by the
font-size, you could simply reset the
0, and thus remove the space between the elements.
font-size: 0 on the parent elements, and then declare a new
font-size for the children elements. This works, as demonstrated here (example)
This method works pretty well, as it doesn’t require a change in the markup; however, it doesn’t work if the child element’s
font-size is declared using
em units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by
Method 3 - Set the parent element to
In some cases, you can also set the
display of the parent element to
This effectively removes the spaces between the elements in supported browsers. Don’t forget to add appropriate vendor prefixes for additional support.
It is incredibly unreliable to use negative margins to remove the space between
inline elements. Please don’t use negative margins if there are other, more optimal, solutions.