How can I get the height of the baseline of a certain font?

fonts, javascript

Solution

I made a tiny jQuery plugin for that. The principle is simple:

In a container, insert 2 inline elements with the same content but one styled very small `.` and the other very big `A`. Then, since there are `vertical-align:baseline` by default, the baseline is given as follow:

       ^ +----+ ^
       | | +-+| | top
height | |.|A|| v
       | | +-+| 
       v +----+

=======================
baseline = top / height
=======================

Here is the plugin in coffeescript (JS here):

$ = @jQuery ? require 'jQuery'

detectBaseline = (el = 'body') ->
  $container = $('<div style="visibility:hidden;"/>')
  $smallA    = $('<span style="font-size:0;">A</span>')
  $bigA      = $('<span style="font-size:999px;">A</span>')

  $container
    .append($smallA).append($bigA)
    .appendTo(el);
  setTimeout (-> $container.remove()), 10

  $smallA.position().top / $bigA.height()

$.fn.baseline = ->
  detectBaseline(@get(0))

then, smoke it with:

$('body').baseline()
// or whatever selector:
$('#foo').baseline()

--

Give it a try at: http://bl.ocks.org/3157389

Problem

I'm hoping to be able to find the height of the baseline of a piece of text in a div using javascript. I can't use a predefined font, because many of my users will be using a larger font setting in their browser. How can I do this in javascript?

Original source