Search code examples
htmlcss

Wrap a text within only two lines inside div


I want to wrap a text within only two lines inside div of specific width. If text goes beyond the length of two lines then I want to show ellipses. Is there a way to do that using CSS?

e.g.

Sample text showing wrapping
of text in only two line...

Solution

  • Limiting output to two lines of text is possible with CSS, if you set the line-height and height of the element, and set overflow:hidden;:

    #someDiv {
        line-height: 1.5em;
        height: 3em;       /* height is 2x line-height, so two lines will display */
        overflow: hidden;  /* prevents extra lines from being visible */
    }
    

    --- jsFiddle DEMO ---

    Alternatively, you can use the CSS text-overflow and white-space properties to add ellipses, but this only appears to work for a single line.

    #someDiv {
        line-height: 1.5em;
        height: 3em;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100%;
    }
    

    And a demo:

    --- jsFiddle DEMO ---

    Achieving both multiple lines of text and ellipses appears to be the realm of javascript.