Hide text if it doesn't fit in one line with CSS

后端 未结 3 1689
清歌不尽
清歌不尽 2021-02-13 18:16

I have a div element which contains some text. This element has fixed width. If the text is so long that it cannot fit in one line, I want to hide that text (the wh

3条回答
  •  终归单人心
    2021-02-13 18:25

    The solutions presented in other comments are out of date, today we have a really simple way to do this using text-overflow.

    Note: The text-overflow: string only works in Firefox.

    Note 2: text-overflow only occurs when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap;.

    .a {
      white-space: nowrap; 
      width: 50px; 
      overflow: hidden;
      text-overflow: clip; 
      border: 1px solid #000000;
    }
    
    .b {
      white-space: nowrap; 
      width: 50px; 
      overflow: hidden;
      text-overflow: ellipsis; 
      border: 1px solid #000000;
    }
    
    .c {
      white-space: nowrap; 
      width: 50px; 
      overflow: hidden;
      text-overflow: "----"; 
      border: 1px solid #000000;
    }

    The text-overflow Property

    The following two divs contains a text that will not fit in the box.

    text-overflow: clip (default):

    Hello world!

    text-overflow: ellipsis:

    Hello world!

    text-overflow: "----" (user defined string):

    Hello world!

    Here you can find an example and a more complete explanation in this article.

提交回复
热议问题