tags:

views:

393

answers:

3

How can I cut a string to fit to the width of a div?

Let's say I have a long string, like "Anyone can help me to solve this problem" to put in a div 80px wide. What I want is to cut the string to fit the width of the div and add "..." at the end of a word, as in "Anyone can help me..."

A: 

I'm pretty sure there's no know where to cut the string. You could use JavaScript to lop off characters one by one until the width is <= 80px, then append a ... but I wouldn't recommend it. A better way would be to crop your string to some length you know will be longer than 80px, then with CSS put overflow:hidden on your div, and overlay your ... as a separate element and align to the right of the div. It might appear slightly off, but I think it's the best you can do. Gmail does something like this. They crop it to a predefined number of characters, slap on a ... and hide anything that's still too long.

Mark
+2  A: 

You could try to use CSS to truncate the string with an ellipsis using methods such as this one by Justin Maxwell.

Basically, to make it work cross-browser, you have to use a combination of standard CSS, browser-specific CSS and some XML. The full writeup can be read at the link above, but the end product is:

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
    -moz-binding: url('assets/xml/ellipsis.xml#ellipsis');
}

combined with

<?xml version="1.0"?>
<bindings
  xmlns="http://www.mozilla.org/xbl"
  xmlns:xbl="http://www.mozilla.org/xbl"
  xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
>
    <binding id="ellipsis">
     <content>
      <xul:window>
       <xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
      </xul:window>
     </content>
    </binding>
</bindings>

Then decorate your div with the CSS class="ellipsis"

Eric King
Touche. I still think its a FF hack though :p
Mark
Mark, I completely agree.
Eric King
A: 

Thanks. I used server script to cut string.

epiece