问题
When I'm making web pages I like to use unicode characters for icons when images or SVGs really aren't necessary. It's easy for me and it makes the page lighter. This works pretty well, usually, except that I always end up having to fiddle with the offset to get it centered correctly.
Yes, yes, I know about this:
.someDiv {
width: 10px;
height: 10px;
line-height: 10px;
text-align: center;
}
But the catch is that most glyphs are not themselves vertically centered. This means that I end up, for example, with this vertically off-center ●
in a square container with that CSS:
Is there a CSS way to center the glyph and not the font's mean line? (Or whatever is technically being centered.)
回答1:
What you are experiencing from my perspective cannot be solved in a satisfactory way. The problem is that a) you are using characters which do have kerning, line-height etc and cannot reliably be centered vertically, not even on a per-character basis, because b) every OS and browser may have their own representations of that character which you cannot control.
I do like the approach nonetheless because being so light-weight, and I used it in the past, e.g. in my minesweeper game https://connexo.de/defuse
All icons you see there are UTF-8 emoji/characters.
回答2:
I was able to achieve something that works reasonably well by ditching CSS and thinking a little more outside the box -
First I downloaded a Noto font with the symbols I want, since Noto fonts are very permissively licensed. https://www.google.com/get/noto/
Then I installed fontforge http://fontforge.github.io/
I added this Python script to my %appdata%/Roaming/fontforge/python/
directory (seeing as I'm on Windows) https://github.com/gumblex/stamico/blob/master/centerglyph.py
I opened the Noto TTF with fontforge. Using select-all then the Tools > Metrics > Center in Glyph
option that the script adds, then some adjusting with Tools > Metrics > Y Offset
I was able to vertically center all the glyphs in the font. (In my case, for some reason, choosing the Center in Glyph/Center in Height options resulted in glyphs that were positioned higher than the center line, so I had to further adjust them.)
I added a @font-face
to my CSS and specified the font style for glyphs that I want to be vertically centered.
@font-face {
font-family: "symbol-font";
src: url(ux/NotoSansSymbols2-Aligned.ttf);
}
来源:https://stackoverflow.com/questions/49839643/how-can-i-center-a-single-unicode-character-vertically-in-a-container