In other words, how do I ignore a character's depth and ascent in instead center it vertically in a surrounding box based just on its bounding box?
Here is a minimal html example:
.box {
display: inline-block;
width: 1em;
height: 1em;
line-height: 1em;
border: 1px solid black;
text-align: center;
}
<span class="box">?</span>
<span class="box">,</span>
<span class="box">`</span>
It produces the following:
How do I change it to produce the following instead?
CSS solutions are preferred if they exist, but Javascript is acceptable as a last resort. I'm looking for a general solution, not just for the three characters pictured. There will be many such boxes in my page, so performance (if Javascript is used) is important.
To clarify things even further, here is how I would do this in LaTeX:
\newlength{\desiredboxsize}
\setlength{\desiredboxsize}{1em}
\newcommand*{\centercharinbox}[1]{%
% Force width
\makebox[\desiredboxsize]{%
% Force height and center vertically
\raisebox{\dimexpr .5\desiredboxsize - .5\height \relax}[\desiredboxsize][0pt]{%
% Cancel depth
\raisebox{\depth}{#1}}}}
To just center the text inside an element, use text-align: center; This text is centered.
To center one box inside another we make the containing box a flex container. Then set align-items to center to perform centering on the block axis, and justify-content to center to perform centering on the inline axis.
Centering a block or image The way to do that is to set the margins to 'auto'. This is normally used with a block of fixed width, because if the block itself is flexible, it will simply take up all the available width. Here is an example: P.blocktext { margin-left: auto; margin-right: auto; width: 8em } ...
The CSS just sizes the <div> , vertically center aligns the <span> by setting the <div> 's line-height equal to its height, and makes the <span> an inline-block with vertical-align: middle . Then it sets the line-height back to normal for the <span> , so its contents will flow naturally inside the block.
In theory, you can do it by aligning every symbol individually.
Practically, you can't as every symbol has its own depth and ascent in the character map, especially using only CSS.
You cannot do that with modern CSS. Neither can you do that out of the box with JavaScript in browsers.
Essentially: you need to get glyph outlines as paths from fonts. Using that information you can get path outline box and render / align in the way you need.
For getting glyph outlines check this How do I get glyph outlines of a letter as bézier paths using JavaScript? answer for example.
Having glyph outline paths you can render them into <canvas>
elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With