1

Add non monospace font, tab space in container, etc...

So how does one derive the width of a text string to be displayed in the container... in em (not px).

This can be useful on devices / website that change the font often. Hence there is no need to "redraw" the size (using the insert, measure, remove) method on every re-size. Some of which has no event to trigger/watch.

Manually using em work so far... the problem is making it automatic. As even jQuery.width() returns its result in px.

2 Answers 2

2

You can convert px into em. Remember the formula:

var em = px / fontSize;

So, if you have a pre element with the font-size set as 1em which is usually 16px, and your width in px is say 800px, then your width in em is 800 / 16 or 50em. Hope that helps. Vote for my answer if you found it useful.

Sign up to request clarification or add additional context in comments.

1 Comment

It's exactly because you asked me to that I'm not voting for your answer...you answer questions on here to offer help, not to gain rep.
0

Not perfect, but gets the job done (somewhat) [uses jQuery]

// [div] : a dom node to test insertion of string (inherits its css prop too)
// [str] : the string to test against
function getEmLen( div, str ) {
    var oriInner = div.innerHTML;
    var res;

    div.innerHTML = '<a>'+str+'</a><a>m</a>';

    res = Math.ceil( 100 * (jQuery(div.firstChild).width()) / (jQuery(div.lastChild).width()) ) / 100; 
    //the * 100, / 100 is to remove long trailing divides

    div.innerHTML = oriInner;
    return ''+res+'em';
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.