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

后端 未结 3 1701
清歌不尽
清歌不尽 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:32

    1. Place your text in an inline-block inner-wrapper with white-space: nowrap to prevent line breaks.
    2. Insert an empty inline-block pseudo-element before that inner-wrapper.
    3. When the inner-wrapper is wider than the outer-wrapper, it will be moved to the second line of the outer-wrapper.
    4. To hide it use overflow: hidden, and set the same value to height and line-height.

    .outer-wrapper {
      overflow: hidden;
      height: 1.2em;
      line-height: 1.2em;
      border: 1px dotted black;
      margin: 1em;
    }
    .outer-wrapper::before {
      content: '';
      display: inline-block;
    }
    .inner-wrapper {
      display: inline-block;
      white-space: nowrap;
    }
    this is a short line
    this is a super long line of text that it is never ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever ever going to fit on a single line!

提交回复
热议问题