I use always following solution when I know icon size.
Pros:
1. Less DOM elements
2. You can modify line-height, font-family, font-size but icon is always perfectly aligned.
div{
position: relative;
padding-left: 20px;
}
div:after{
content: "";
position:absolute;
left: 2px; /*2px gaps between div left edge and icon, icon and text*/
top: 50%;
width: 16px;
height: 16px;
margin-top: -8px;
}
> The ex unit can be useful because it’s based on the x-height—the height of the letter X.
Just to be more exact. ex unit is the height of the lowercase "x".
I usually use verical-align: -1.em
: possible because of display: inline-block
. It's a little more cross browser than transforms and, as far as I know, doesn't create a new context.
I believe the offset could also be generalized as
$height: 1em; // any height, any unit .icon { display: inline-block; height: $height; vertical-align: calc((1em - 1ex)/4 - ($height - 1ex)/2); }
whoops, bad formatting. this:
// Sass
$height: 1em; // any height, any unit
.icon {
display: inline-block;
height: $height;
vertical-align: calc((1em - 1ex)/4 - ($height - 1ex)/2);
}
When using:
.icon {
width: 16px;
height: 16px;
display: inline-block;
background-color: salmon;
vertical-align: middle;
transform: translateY(-.1em);
}
How does the -0.1em hold up over a range of possible text sizes?
I usually give height and line-height the same value to achieve the same result.
div {height: 16px;line-height: 16px;}
Percentages can also be used.
vertical-align: 50%
+1 for using line-height, always fixes it for me.
Huh, I did not know that vertical-align took a percentage (of line-height) or a length (both relative to the parent baseline).
Nice.
The problem surrounds your choice of markup. Unless you are deliberately using the bare minimum; creating what seems (to me) to be an edge/use case. Personally I would either use a pseudo element and wrap a span around the text. Then set both to inline-block and apply vertical align[whatever] to both the span and the pseudo element. Why not do that instead? Or does this have to work only the specific situation you have demonstrated?
Life saver, works for me with fontello.
@Morgan Feeney: That works if the text next to the icon doesn't need to wrap. While minor, it also means creating an extra class along with the extra HTML. Byte for byte, I don't think you end up ahead.
I often use tricks like top, bottom or line-height to fix this stuff. Now I see the heaven. Thanks alot J
I usally use
line-height:0
or sometimes1px
. It makes it easier to control the vertically centering, I think.