Trim 字符串给定 space 而分词多行

Trim string for given space while word break multiline

我有一个边栏,我想在其中提供最多两行的标题和说明。但是,跨度的高度应始终为两行,以便具有相同的垂直对齐方式。另外,我不希望最后一个词中断,它应该用 ... 替换它。例如,如果最后一个单词不适合给定的 space,它不应该将单词分成下一行,而应该像这样 this is my descirpti....

单词应该被剪切并附加 ...

此外,是否可以在文本被剪切的每个 div 处添加一个 class?我想为这些箱子设计一种特殊的风格!

我想用 CSS 属性 text-overflow

来解决这个问题

.max-width-200 {
  max-width: 900px;
}

span {
  overflow: hidden;
  text-overflow: ellipsis;
}

.heading-wrapper ,.description-wrapper {
  height: 50px
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container">
   <div class="row max-width-200">
      <div class="col-3">
         <img src="https://picsum.photos/180">   
      </div>
      <div class="col-7 d-flex flex-wrap">
         <div class="col-12 no-padding align-self-start heading-wrapper">
            <span>This is my heading, its not very long</span>
         </div>
         <div class="col-12 no-padding align-self-center description-wrapper">
            <span>This is my description. This description is longer then it should be. It should only be two rows large but unfortuntly its longer then two rows.</span>
         </div>
      </div>
   </div>
   <hr>
   <div class="row max-width-200">
      <div class="col-3">
         <img src="https://picsum.photos/180">   
      </div>
      <div class="col-7 d-flex flex-wrap">
         <div class="col-12 no-padding align-self-start heading-wrapper">
            <span>This is my heading, Its longer then it should be.. someone fucked it up. Please fix me to be only two rows long!</span>
         </div>
         <div class="col-12 no-padding align-self-center description-wrapper">
            <span>This is my description. This description is longer then it should be. It should only be two rows large but unfortuntly its longer then two rows.</span>
         </div>
      </div>
   </div>
</div>

您可以使用:

  span {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-line-clamp: 2;
   -webkit-box-orient: vertical;
  }

通常 text-overflow: ellipsis; 需要设置 white-space 属性才能工作。参见:https://whosebug.com/a/7680712/8177490

您还应该在使用前检查浏览器兼容性。

如果您不希望标题受到影响,请将其标签从 span 更改为 p 或某些 h 标签。