动态宽度跨度与文本溢出

时间:2016-02-14 16:49:51

标签: html css

我遇到了一些问题,试图让text-overflow: ellipsis在我没有固定宽度的范围内工作。跨度应根据内容进行扩展,但如果内容大于可用空间,则内容应显示省略号。这是指向JSFiddle的链接。

CSS和HTML:



.row {
    width: 50%;
    border: 1px solid black;
}

.wrapper {
    text-align: left;
}

.label {
    display: inline-block;
    margin-top: 10px;
    margin-right: 4px;
    padding: 0 8px;
    border-radius: 4px;
    color: white;
    background-color: grey;
    height: 20px;
    vertical-align: middle;
    font-size: 14px;
}

.content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

<div class="row">
    <div class="wrapper">
        <div class="label">
            <span class="content">text</span>
        </div> 
        <div class="label">
            <span class="content">longer text label</span>
        </div>
        <div class="label">
            <span class="content">Another label</span>
        </div>
        <div class="label">
            <span class="content">A very very very very very very long text label that should fit inside row and cut the text and show ellipsis...</span>
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

检查这个plunker:

https://jsfiddle.net/42khut93/3/

您需要为max-widthlabel类设置content 并按百分比调整填充 同时将.content display设置为blockinline-block

&#13;
&#13;
.row {
  width: 50%;
  border: 1px solid black;
}
.wrapper {
  text-align: left;
}
.label {
  display: inline-block;
  margin-top: 10px;
  margin-right: 4px;
  padding: 0 1%;            //in percentage
  border-radius: 4px;
  color: white;
  background-color: grey;
  height: 20px;
  vertical-align: middle;
  font-size: 14px;
  max-width: 98%;          //max-width 100% - 1% padding + 1% padding  
}
.content {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;         // set max-width
}
&#13;
<div class="row">
  <div class="wrapper">

    <div class="label">
      <span class="content">text</span>
    </div>

    <div class="label">
      <span class="content">longer text label</span>
    </div>

    <div class="label">
      <span class="content">Another label</span>
    </div>

    <div class="label">
      <span class="content">A very very very very very very long text label that should fit inside row and cut the text and show ellipsis...</span>
    </div>

  </div>
</div>
&#13;
&#13;
&#13;