开发者

How to vertically align the baseline of text to a set point in HTML/CSS?

开发者 https://www.devze.com 2023-03-20 09:27 出处:网络
I have created an algorithm that converts text formatted in SVG into HTML, the algorithm works well but the positioning of the text in the HTML version is slightly out compared to the SVG.

I have created an algorithm that converts text formatted in SVG into HTML, the algorithm works well but the positioning of the text in the HTML version is slightly out compared to the SVG.

I have realised that this is due to the coordinate system in SVG; it's origin is at the bottom left rather than the top left. Therefore my HTML text is below the position it should be. This is for commercial software, personally I would rather keep the text as SVG, but I can't because of a client request, also this needs to be a pixel perfect copy!

In order to fix the HTML I need to align the text so that its baseline is at the point that I read from the SVG. I have tried to do this with vertical-alignment but with no success.

The problem is not working out the coordinates here, I already know where the baseline of the text should be.

Does anyone know how to to align the baseline of some text to a set point in HTML? Or does anyone know if it is even possible to place text using the baseline rather than the top l开发者_高级运维eft point.


CSS can't change the position of the baseline. It is where it is, based on the font.

I would love to do this by trial an error but this needs to work for any SVG file, which could use any font, at any size. Therefore the margin is going to be different each time.

That rules out any kind of "hack" to make it look right..

Take a look at all the possible values for vertical-align.

If none of those help, I don't know what to suggest.


line-height should work for you. But to be honest, your going to need to play around with a few things, like padding, margin to get it just right.


You should be able to define the location using divs bottom and left (or whatever you have each line of text set as) CSS properties (and make sure that it's position is set to absolute).


Workaround

One way will be to wrap your fonts in an element to allow vertically nudging it in the viewport.

<style>
.font-vertical-fix {
  position: relative;
  bottom: -0.2em;
}
</style>

<span class="font-vertical-fix">
  Some badly designed font family ported to the web.
</span>

Example: https://jsfiddle.net/rkc3ho48/

Solution

The solution is to use a Webfont that's designed for the web.

Not all fonts made for desktop apps like Adobe/Sketch are designed with the web in mind. On these platforms, the designer can just vertically nudge the font in the canvas.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号