Last Updated: February 25, 2016
·
1.291K
· arti5m

Getting the baseline of a certain font

Stack Overflow: <a href="http://stackoverflow.com/questions/10247132/how-can-i-get-the-height-of-the-baseline-of-a-certain-font">How can I get the height of the baseline of a certain font?</a>

User abernier created a clever jQuery plugin that calculates the baseline for a font rendered in a web page. It inserts two inline elements (one small, one tall, neither with descenders): "." and "A". baseline = top / height

var $, detectBaseline, _ref;

$ = (_ref = this.jQuery) != null ? _ref : require('jQuery');

detectBaseline = function(el) {
  var $bigA, $container, $smallA;
  if (el == null) {
    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((function() {
    return $container.remove();
  }), 10);
  return $smallA.position().top / $bigA.height();
};

$.fn.baseline = function() {
  return detectBaseline(this.get(0));
};

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside