Search code examples
javascriptcsslessmultilineellipsis

hide css3 multiline ellipsis read more link when there is no use


I have a little problem. I figured out a way to use cross-browser multiline ellipsis.

Here is my less CSS mixin.

As you can see, this version works perfect in webkit and "ok" in all other browsers.

.ellipsis-multi(@lh, @l, @mw) {
  /* non-webkit */
  max-height: @lh*@l;
  /* webkit */
  -webkit-box-orient: vertical;
  -webkit-line-clamp: @l;
  display: -webkit-box;
  line-height: @lh;
  max-width: @mw;
  overflow: hidden;
  text-overflow: ellipsis;
}

.excerpt {      
  &.hide {
    .ellipsis-multi(1.4em, 3, 100%)
  }
}

My problem is, I use a read-more link to add and remove the class "hide". This works perfect, but the link is also visible if the excerpt div only has 2 lines of text.

I need a way to just show the link if the ellipsis is needed.

Here is a Codepen example http://codepen.io/janwagner/pen/ubHef

I would prefer a CSS only way to fix this :)


Solution

  • There is no way you can do this with CSS only. However, you can use the following function to count the number of lines you have:

    var divHeight = $('.excerpt p').height();
    var x = ('.excerpt p').css('line-height');
    lineHeight = parseInt(x); // Returns clean line-height
    var lines = divHeight / lineHeight; // Returns number of lines
    

    And then simply use an if statement to either show or hide the read more button depending on how many lines the paragraph has. Something like this:

    if(lines > 4){
    $('.readmore').show;
    }else{
    $('.readmore').hide;
    }