Dan
Dan

Reputation: 57881

Get dimensions of text block via JavaScript, not the size of container's `getBoundingClientRect`

I want to get the size of text inside a container. Let's consider general case when the container has padding and border.

The problem is that getBoundingClientRect returns the size of text PLUS left border and padding, in case the text overflows. Otherwise it returns just the size of border box of the container.

enter image description here

Upvotes: 8

Views: 1164

Answers (3)

Dan
Dan

Reputation: 57881

People who had answered here came with a brilliant idea of wrapping the text into a <div> having zero margin, border and padding;

I just developed the idea further. I place the div inside the container, making the text have exactly the same style as it had without wrapper.

JsFiddle

This solution will work almost everywhere. It can be broken by not very encouraged way of writing CSS, like

.container div b {
    padding: 5px;       /* firing only when test is run */
}

If you do not code CSS in you project like that, you are the lucky one to use my snippet )

Upvotes: 0

Barry T. Smith
Barry T. Smith

Reputation: 1051

Interesting! You could use javascript to clone the text inside of an empty element offscreen that has 0 padding/margin/border. Then you could get the width of that element.

var txt = document.getElementById('fixed').innerHTML,
    clone = document.getElementById('clone');

clone.innerHTML = txt;

var width = clone.offsetWidth;

document.getElementById('output').innerHTML = width;
#fixed {
    width: 8em;
    height: 8em;
    border: .5em solid red;
}

#clone { 
  margin: 0;
  padding: 0;
  border: 0;
  position: fixed;
  left: -9999px;
}
<div id="fixed">asdfkjahsdflkahjsdflkjhasdljfhalsdkjfhalsdkjfhalsdkjfhalksdhjflasd</div>
<div id="clone"></div>

Width of text: <span id="output"></span>

Upvotes: 2

Liftoff
Liftoff

Reputation: 25392

You can get the width if you create a placeholder div with all of the same text formatting options and find it's width.

For instance, I will create a div with the class .hidden that has the same attributes as the original div.

div.container
{
    font-size: 16px;
}

div.hidden
{
    font-size: 16px;
    display: none;
}

Then, using jQuery, copy the contents of .container to .hidden and find the width of .hidden:

$(function(){

    $("div.container").each(function(){
   
        $("body").append("<div class='hidden'>"+$(this).html()+"</div>");
        var width = $("div.hidden").width();
        $("div.width").html("Actual width: "+width+"px");
        $("div.hidden").remove();
    
    });

});

JSFiddle

Upvotes: 2

Related Questions