🏠 Games Tutorials Dev blog JS code golf Other projects

Text experiments

June 2013 - January 2014


Multiline ellipsis

CSS ellipsis are handy but they only work with one line of text.

On modern browsers, multiline ellipsis can be achieved with -webkit-line-clamp + text-overflow: ellipsis (SEE DEMO).

Here's an alternative that works on IE and written in just 10 lines of JS code, plus a bit of CSS:

// Detect if the ellipsis is necessary and set the "overflow" class accordingly
function toggleEllipsis(p){
  
  // Try to scroll 1px inside the element
  p.scrollTop = 1;
  
  // Measure the element's scroll
  // If it's 1, it means that the elements has an overflow
  if(p.scrollTop){
    p.scrollTop = 0;
    p.className = "overflow";
  }
  
  // Else, no overflow
  else{
    p.className = "";
  }
}

DEMO


Smart text alignment

I developed a pure CSS solution that allows to have some text centered inside a container when it's short (less than one line), and aligns it to the left when it's long (2+ lines). It works on all browsers, including IE6.

Simple case: text "center-left"

HTML code:

<div class=align-outer>
  <div class=align-inner>
    Text text text
  </div>
</div>

CSS code:

.align-outer {
  text-align: center;
}
.align-inner {
  margin: 0 auto;
  text-align: left;
  display: inline-block;
  *display: inline; *zoom: 1; /* IE < 8 */
}

Demo:

Text text text text text



More complex case: text "centered-stretchable-left"

I also made a more generic solution that allows to center the text in a defined zone when it's short, and enlarging this zone when it's long (works on IE8+).

HTML code:

<div class=align-stretch-outer>
  <div class=align-stretch-inner-1>
    <div class=align-stretch-inner-2>
      Text text
    </div>
  </div>
</div>

CSS code:

.align-stretch-outer {
  text-align: left;
}
.align-stretch-inner-1 {
  display: inline-block;
  text-align: center;
  min-width: 60%;
}
.align-stretch-inner-2 {
  display: inline-block;
  text-align: left;
}

Demo:

Text text

NB: of course, you can replace left by "right" or "justified" in the first CSS rule.