在断行多行时修剪给定空间的字符串

问题描述

我有一个侧边栏,我希望标题和描述最多两行。但是,跨度的高度应始终为两行,以具有相同的垂直对齐方式。另外,我不希望最后一个单词中断,它应该只用...代替。例如,如果最后一个单词不适合给定的空格,则它不应该只是将单词分解为下一行,而应像这样this is my descirpti...

该单词应被删节并附加...

还可以在每个被剪切文本的div添加一个类吗?我想为这些情况设计特殊风格!

我想使用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://stackoverflow.com/a/7680712/8177490

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

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