📜 ⬆️ ⬇️

Alignment of icons by font baseline

Good day. In this short note I will explain how to cross-align the icons with the base line of the font. So, the task at first glance is rather trivial: in the layout that the designer sent there is the following, very standard, block (the username in the header after the user logged into the site)

image


')
Without hesitation, we write simple markup and css to it:

HTML
<div class="user"> <span class="user-icon"></span> <span class="user-name">User Name</span> </div> 

CSS
 .user-icon { width: 23px; height: 20px; background: url('person.png'); display: inline-block; margin-right: 3px; } .user-name { font-size: 14px; } 

After that, we open the page in all browsers and see that everything works as it should, since all inline and inline-block elements are by default aligned to the baseline of the font. However, IE as usual presents a surprise. I understand that IE6 is already breathing its last, but now with IE7 you have to reckon with it, and the above code is rendered in it as follows:

image

Not sure exactly what the reason for this behavior is, but most likely this is due to the incorrect operation of the display: inline-block property in IE6-7.
Moreover, if instead of the background with a background we put a regular picture, then everything is perfectly aligned, but this solution does not suit us, since all the icons are sewn into the sprite, which does not allow us to use ordinary pictures.
The solution came pretty quickly: you just need to push another empty span into the span, which forcibly causes the entire block, whatever its size, to align with the baseline.
And our HTML then begins to look like this:

 <div class="user"> <span class="user-icon"><span></span></span> <span class="user-name">User Name</span> </div> 

That's all. Thanks for attention.

Upd. one



For those who do not understand, why put an icon as a separate element, and not just a background with text, I explain:

1. First, the solution with the background depends on the height of the line. If the height of the icon is greater than the height of the line, it will be clipped. And the height of the line is such a value in which you can never be 100% sure; in different situations, in different browsers, on different platforms, it can be calculated in completely different ways.

2. Secondly, the height of the line depends on the font size and typeface. Therefore, if the user suddenly changed the font size in his settings, then all your positioning will immediately fly to hell.

Source: https://habr.com/ru/post/136746/


All Articles