August 24, 2015

CSS Truncation Mixin

I want a be-all and end-all CSS solution for text truncation on the web. I’ve lost count of how many times I’ve come across projects where I’ve done this same thing over and over. Some solutions were good, some bad; some Javascript, some CSS.

I finally came across a CodePen by Ronny Siikaluoma which has come up with a very clever CSS only solution.

The Class

.line-clamp {
  display: block;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  overflow: hidden;
  padding: 0 !important;
  position: relative;
  text-overflow: ellipsis;

  &:after {
    background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 75%);
    content: "";
    display: block;
    position: absolute;
    right: 0;
    text-align: right;
    width: 25%;
    height: 1rem * 1.5;
  }
}

@supports (-webkit-line-clamp: 1) {
  .line-clamp:after {
    display: none !important;
  }
}

What is @supports? It’s a simple way to detect if a browser supports a given CSS property, or not. It’s fairly well supported now-a-days, but will be perfect for our webkit-only line-clamp feature we’re using here.

The Mixin

@mixin line-clamp($lines) {
  .line-clamp--#{$lines} {
    -webkit-line-clamp: $lines;
    height: 1rem * 1.5 * $lines;
    &:after {
      top: 1rem * 1.5 * ($lines - 1);
    }
  }
}

Note: This mixin only creates a CSS rule. You don’t want to use it within a rule.

###Create your rule Now just include the mixin and adjust the line count for your needs. The example below will output a class modifier .line-clamp--2 to use on the elements you would like to truncate.

@include line-clamp(2);

Example

See the Pen 7e95cf31cbb709792eeb48a3ad5dc375 by Ryan McLaughlin (@ryanmclaughlin) on CodePen.