This is the third article I participated in getting started. When displaying text, we all encounter that text is too long, which affects the size of the box and thus the overall layout. So I will show you some ways to hide text that is too long beyond the designated area.

First, the most common solution is to set the box property text-overflow. This property can set text overflow to appear as ellipses, but this property can only hide one line of text overflow, so we also need to make the text not newline.

.text {
    width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
Copy the code

The above can only show a single line hiding can not achieve multi-line hiding, if we want to achieve multi-line text hiding can be achieved through pseudo class. We’re going to limit the width and height of the box and then we’re going to overflow and hide it, and then we’re going to set a pseudo-class to ellipsis and we’re going to hide it by moving it to the bottom right of the box, but if we don’t have that much text, we’re not going to overflow but the ellipsis is still there, So we’re going to use another pseudo-class to hide the ellipsis when the text doesn’t overflow.

.text {
    position: relative;
    max-width: 450px;
    max-height: 3.6 rem;
    line-height: 1.2 rem;
    font-size: 16px;
    overflow: hidden;
    padding-right: 10px;
    text-align: justify;
}
.text::before {
    position: absolute;
    content: '... ';
    right: 0;
    bottom: 0;
}
.text::after {
    position: absolute;
    content: ' ';
    width: 11px;
    height: 100%;
    right: 0;
    background: #fff;
    z-index: 1;
}
Copy the code

Line-clamp property can also be used to limit the number of lines displayed in the content, but setting overflow hiding through this property may not be so compatible. To use this property, you need to set the other two properties, otherwise there will be no effect. First, set the box display to box. Then set the box-orient:vertical property, which specifies that the content can be displayed in multiple lines, with a browser prefix.

Above you can see that the ellipsis appears after three lines, but the text still overflows so we also need to set overflow property.

.text {
    width: 250px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
}
Copy the code