11

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?

0

3 Answers 3

14

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

2
  • A more complete alternative could be using pomax.nihongoresources.com/pages/Font.js — haven't tried it yet but seems great.
    – abernier
    Commented Aug 4, 2012 at 13:05
  • 1
    Hi @abernier. I have tried your code and when I run it I get the number 1.1108247422680413 for the baseline on what I assume is the default font for my web site. Can you tell me what that number means? I have worked out the baseline by eye and I can't see how the number I get from your method relates to it. Thanks in advance. Commented Jul 3, 2015 at 7:22
5

Following the discovery by Alan Stearns (http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/) that inline-block elements change the baseline alignment of other inline elements, I put together a demo which I found more accurate than https://stackoverflow.com/a/11615439/67190, and actually more simple to derive a value in JavaScript: http://codepen.io/georgecrawford/pen/gbaJWJ. Hope it's useful.

<div>
  <span class="letter">T</span>
  <span class="strut"></span>
<div>
div {
  width: 100px;
  height: 100px;
  border: thin black solid;
}
.letter {
  font-size: 100px;
  line-height: 0px;
  background-color: #9BBCE3;
}
.strut {
  display: inline-block;
  height: 100px;
}
3
  • alas, your solution does not seem to work on firefox 37
    – jedierikb
    Commented May 7, 2015 at 14:43
  • Hi @George Crawford. Thanks for your code and demos. Is there a document/drawing that explains what the various values that your method returns relate to? The font and the lineheight are obvious. From studying your demos I think the baseline is the decender size and the content is the total size of the font, i.e. decender + cap height + ascender, but I might be wrong. A nice table or picture would be helpful. Commented Jul 3, 2015 at 8:07
  • Hi @George Crawford. Sorry - I see that you have got a diagram on one of your examples. Very helpful Commented Jul 11, 2015 at 13:05
2

Vanilla JS, no font info required tested on Chrome, Firefox and Edge :

function getBaselineHeight(el){
    let bottomY = el.getBoundingClientRect().bottom;//viewport pos of bottom of el
    
    let baselineLocator = document.createElement("img"); // needs to be an inline element without a baseline (so its bottom (not baseline) is used for alignment)
    el.appendChild(baselineLocator);

    baselineLocator.style.verticalAlign = 'baseline' ; // aligns bottom of baselineLocator with baseline of el
    let baseLineY = baselineLocator.getBoundingClientRect().bottom;//viewport pos of baseline
    el.removeChild(baselineLocator);
        
    return (bottomY - baseLineY) ;        
}

function positionLine(){
    let line = document.getElementById("line");
    let lorem = document.getElementById("lorem");
    let baselineHeight = getBaselineHeight(lorem);
    let newLinePos = lorem.getBoundingClientRect().bottom - baselineHeight ;
    line.style.top = newLinePos + "px" ;

}
#lorem{
    background-color: lightblue;
}
#line{
    position:absolute;
    left : 0 ;
    height:1px;
    width:100%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
        <span id="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit..</span>

        <br><br>

        <button class="btn btn-primary" onclick="positionLine();">position line on baseline</button>

        <br><br>

        <svg id="line">
            <line x1="0" y1="0" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:1"></line>
        </svg> 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.