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 html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script type="text/javascript">
        function txtContent_onchange()
        {
            var span = document.getElementById("spanMeasure")
            span.innerHTML = "";
            span.appendChild(document.createTextNode(this.value));
            document.getElementById("txtWidth").value = span.scrollWidth;

        }
    </script>
    <style type="text/css">
        #spanMeasure 
        {
            position:absolute;
            top:0px;
            left:0px;
            visibility:hidden;
            width:10px;
            white-space:nowrap;
            overflow:hidden
        }
    </style>
</head>
<body>

    <input id="txtContent" onchange="txtContent_onchange.call(this)" /><br />
    <input id="txtWidth" />
    <span id="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"