Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the baseline of text

I am trying to write a test to work out whether the text rendered inside an <input> has the same baseline as a label:

label adjacent to input with baselines highlighted

In order to do this, I would like to compute the baseline of the text that has been rendered in each element and compare the two values. Is this possible and if so, how is it done? If not, is there a better way to establish that the baseline of the two elements is the same?

I have found a way to determine the baseline of the label which seems to work reliably:

function getBaseline(element) {
    var span = document.createElement("span");
    span.setAttribute("style", "font-size:0");
    span.innerText = "A";
    jQuery(element).prepend(span);
    return span.getBoundingClientRect().bottom;
}

However, this method doesn't work for the <input>, as I cannot insert the span in that case.

like image 654
Tom Fenech Avatar asked Oct 31 '22 22:10

Tom Fenech


1 Answers

I found a way to get the computed baseline based on your function. The trick is to create a wrapper and apply all styles from the element to it. I can confirm that it works in Firefox (v38) and Chrome (v44) on OSX. Unfortunately it doesn't work proper in Safari.

DEMO

function getBaseline(element) {
    element = jQuery(element);
    var span = document.createElement("span");
    span.setAttribute("style", "font-size:0");
    span.innerText = "A";

    var wrapper = document.createElement("span");
    applyCSSProperties.call(wrapper, element);
    element.wrap(wrapper);
    element.before(span);

    var computed = span.getBoundingClientRect().bottom;

    span.remove();
    element.unwrap(wrapper);

    return computed;
}

function applyCSSProperties(element) {
    var styles = {};
    var comp = getComputedStyle(element[0]);

    for(var i = 0; i < comp.length; i++){
        styles[comp[i]] = comp.getPropertyValue(comp[i]);
    }

    jQuery(this).css(styles);
}
like image 161
damian Avatar answered Nov 12 '22 13:11

damian