CSS:将文本剪切为父<div>的大小

时间:2017-04-12 13:10:36

标签: html css

问题是在孩子<div>中尽可能多地垂直拟合文本而不让孩子<div>超出父容器<div>并且不知道剩余空间的数量父容器提前。

容器有一个固定的高度和两个孩子。以下是HTML代码段示例:

<div class="container">
  <div class="title">
    The title, this must grow as much as needed
  </div>
  <div class="text">
    Some text that goes beyond the size of the container. I want this text to be cut with ellipsis when the container "ends"
  </div> 
</div>

和相应的样式表:

.container {
  width: 15rem;
  background-color: yellow;
  height: 20rem;
}

.title {
  font-size: 200%;
  font-wieght: 600;
}

.text {
  text-overflow: ellipsis;
  border: 2px solid red;
}

第一个孩子(标题)必须使其大小适应所包含的文本。另一个孩子必须使用剩​​余的垂直空间,但不得超过其父级的fizex高度。

This jsfiddle显示了我想要实现的目标。

我只需要一个CSS解决方案,没有Javascript可能。如果需要,我可以更改HTML结构。

在将overflow: hidden添加到容器的提示之后编辑:

由于做了我需要的东西似乎不可能,我可以没有省略号,所以overflow: hidden解决方案对我来说没问题。但是我已经尝试过,但似乎没有用:

https://jsfiddle.net/lucrus/8ux1h309/5/

2 个答案:

答案 0 :(得分:1)

使用Flexbox非常简单。您只需要在父元素上使用flex: 1,在要继续使用其他元素的元素上使用overflow: hiddenellipsis。但是如果你想要现在很难用css做多行文本溢出.container { width: 15rem; background-color: yellow; height: 20rem; display: flex; flex-direction: column; } .title { font-size: 200%; font-weight: 600; } .text { border: 2px solid red; overflow: hidden; flex: 1; }

<div class="container">
  <div class="title">
    The title, this must grow as much as needed
  </div>
  <div class="text">
    Some text that goes beyond the size of the container. I want this text to be cut with ellipsis when the container "ends".<br/><br/>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br/>
     Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>
{{1}}

答案 1 :(得分:0)

您需要将overflow: hiddenwhite-space: nowrap添加到.texthttps://jsfiddle.net/dgrijuela/8ux1h309/3/

但是只显示2行(因为nowrap),text-overflow: ellipsis仅适用于nowrap,因此不可能在段落的末尾加上省略号。

如果您希望剪切段落(没有省略号),请将overflow: hidden应用于.container