text-overflow:CSS的省略号属性无法正常工作

时间:2015-06-26 19:12:02

标签: html css

我正在尝试在具有动态高度的HTML div上使用CSS text-overflow:ellipsis属性。 JS小提琴链接是https://jsfiddle.net/GS2306/bj8jg6nc/1/

#first {
    max-height: 310px;
    width: 300px;
    border: 1px solid red;
}
.one {
    max-height: 150px;
    width: inherit;
    border: 1px solid blue;
    font-size: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    min-height: 100px;
    white-space: nowrap;
}
.two {
    height: 100px;
    width: inherit;
    border: 1px solid green;
}

我无法看到占据可用空间的全文。

但是当我从div中删除“white-space:nowrap”属性并使用类“one”时,我可以看到文本占用了可用空间。 https://jsfiddle.net/GS2306/bj8jg6nc/2/

如何在这种情况下使文本占据最大宽度150 px,并将溢出的文本显示为剩余部分的省略号

1 个答案:

答案 0 :(得分:0)

You might consider using display: -webkit-box and having line-clamp: <num> will be a fix. You want X lines of text. Anything after that, gracefully cut off. That's "line clamping" and it is a perfectly legit desire.

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,700);
* {
  margin: 0;
  padding: 0;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  padding: 3em 2em;
  font-family: 'Open Sans', Arial, sans-serif;
  color: #cf6824;
  background: #f7f5eb;
}

h2 {
  display: block;
  /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: 109.2px;
  /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: 26px;
  line-height: 1.4;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<h2>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et.</h2>

And with your markup.

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,700);
* {
  margin: 0;
  padding: 0;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  padding: 3em 2em;
  font-family: 'Open Sans', Arial, sans-serif;
  color: #cf6824;
  background: #f7f5eb;
}

.one {
  display: block;
  /* Fallback for non-webkit */
  display: -webkit-box;
  max-width: 400px;
  height: 72.2px;
  /* Fallback for non-webkit */
  margin: 0 auto;
  font-size: 26px;
  line-height: 1.4;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div id="first">
  <div class="one">Using text-overflow is a difficult skill to master. Please help me with your comments</div>
  <div class="two"></div>
</div>

Some references you might consider interesting: