Skip to content Skip to sidebar Skip to footer

Knowing How Wide A Text Line Will Be In Html For Word Wrap And Other Applications

Do you know a good cross-browser way of knowing how wide will be a text line so you can break it exactly to fit a fixed width? Suppose you want to break a long text like so it does

Solution 1:

Here is a complete "Heath Robinson" (does that reference travel well?) approach.

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><scripttype="text/javascript">functiontxtContent_onchange()
        {
            var span = document.getElementById("spanMeasure")
            span.innerHTML = "";
            span.appendChild(document.createTextNode(this.value));
            document.getElementById("txtWidth").value = span.scrollWidth;

        }
    </script><styletype="text/css">#spanMeasure 
        {
            position:absolute;
            top:0px;
            left:0px;
            visibility:hidden;
            width:10px;
            white-space:nowrap;
            overflow:hidden
        }
    </style></head><body><inputid="txtContent"onchange="txtContent_onchange.call(this)" /><br /><inputid="txtWidth" /><spanid="spanMeasure"><span></body></html>

The critical thing here is the configuration of the span element. This element will not impact the visual appearance of the page. Its scrollWidth property will return the length of the text it contains. Of course you would need to set any font style attributes to get a reasonable value.

According to quirksmode site Opera may be a little flaky with this approach but I suspect its the closest you will get to a fully cross-browser solution.

Post a Comment for "Knowing How Wide A Text Line Will Be In Html For Word Wrap And Other Applications"