By utilizing the CSS property vertical-align: middle
, you can adjust the image to align with the height of the text. As depicted in the screen-capture I provided, the image is perfectly positioned between the top and bottom of the text (highlighted by two green lines).
https://i.sstatic.net/mgpN0.png
The space that appears empty between the text and the top border is determined by how a specific font arranges its characters within its internal height, which can vary across different fonts.
If, for any reason, you wish to override this default behavior and precisely position an image within the internal height of a font (as described in your query), you will need to introduce some margin adjustments.
To maintain normal text flow, consider taking these steps:
- Add a few pixels of margin or padding to the image element
- Include additional transparent pixel lines on the image
Note: Achieving perfection in alignment may require custom calculations for the margin based on the font being used, its size, and potentially cross-OS testing.
To centrally align text/image elements, you could try:
- Employing
display: table
(compatible with IE8/9)
- Utilizing
display: flex
(not supported in IE8/9)
Below are code snippets showcasing the use of "padding" and display: table
:
/* padding */
span img {
padding-bottom: 3px;
width: 20px;
vertical-align: middle;
}
/* display table */
div {
display: table-cell;
vertical-align: middle;
padding: 5px;
}
div span {
vertical-align: middle;
}
div img {
width: 20px;
vertical-align: middle;
}
<span style="padding: 5px;border: 1px solid black; background-color: #CCCCFF"> This one
<img
src="http://files.softicons.com/download/social-media-icons/stucco-social-media-icons-by-bradley-siefert/png/64x64/stucco-facebook.png"> use padding </span>
<br /><br />
<div style="border: 1px solid black; background-color: #CCCCFF">
<span>This one</span>
<img src="http://files.softicons.com/download/social-media-icons/stucco-social-media-icons-by-bradley-siefert/png/64x64/stucco-facebook.png">
<span>use display: table</span>
</div>