To solve this issue, simply use the CSS property vertical-align: middle
.
Since images are treated as inline elements, they behave similarly to regular characters like letters. By aligning the image in the middle of the line, you can magically eliminate any gaps. Take a look at the updated example on this Fiddle.
You have the option to apply this alignment specifically for images inside tables or site-wide (which is recommended when starting a new project). This adjustment can be included in reset.css or html5 boilerplate.
td img { vertical-align: middle; } /* Applies only to images within tables */
/* OR */
img { vertical-align: middle; } /* Fixes alignment for the entire site */
EDIT
Based on feedback from comments, let's explore further with this Fiddle
Consider the first paragraph with underlined text. Notice how 'hanging letters' like 'g', 'p', and 'y' extend below the baseline. Characters are aligned based on the bottom portion of a standard character such as 'c', 'h', 'a', etc.
This concept also applies to images when they are inline elements. The browser reserves space for potential hanging parts of characters or images within a line of text. Therefore, explicit alignment is necessary to ensure proper display.
Additional examples showcase top, middle, and bottom alignments. In unaligned paragraphs, space is reserved for hanging parts, which is eliminated in properly aligned versions where the lowest part defines the edge of the element.
Hopefully, this explanation sheds light on the technicalities and enhances understanding :)
One important note: while using display: block
may temporarily fix the issue, it is not recommended for all scenarios as images do not always need to act as block elements. For a universal solution, include img { vertical-align: middle; }
at the beginning of your stylesheet.