基于宽度同级图片宽度的CSS剪辑字符串

时间:2018-09-08 22:24:11

标签: html css

是否可以在不定义绝对宽度的情况下裁剪(使用椭圆)字符串? 我知道如果设置了绝对宽度,以下类将起作用:

div {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

但是,如果文本的宽度超过下图的宽度,我希望将其剪切(带有椭圆):

<div>@graphic.Name</div>
<img src="@graphic.ApplicationFilePath" alt="" />

1 个答案:

答案 0 :(得分:0)

您可以将两个元素都包装到与inline-block相同的包装器中。 您将文本位置设置为绝对,以便仅图像将定义容器的宽度,然后使用left / right

将文本拉伸到该宽度

.container {
  position:relative;
  display:inline-block;
}
.container > div {
  position:absolute;
  top:0;
  left:0;
  right:0;
  text-overflow:ellipsis;
  white-space:nowrap;
  overflow: hidden;
}
.container > img {
  margin-top:20px; /*you need to adjust this depending on the height of the text*/
}
<div class="container">
  <div>this is a long long text</div>
  <img src="https://picsum.photos/100/100?image=1069">
</div>

<div class="container">
  <div>this is a long long text</div>
  <img src="https://picsum.photos/150/150?image=1069">
</div>