admin管理员组

文章数量:1123381

I have a container which has some text. As the size of the container is reduced, the text must be truncated. But I want the truncation to only happen till a specific minimum width of the container beyond which the text should be hidden. Is it possible to achieve this using only CSS?

.container {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<div class="container">
  This is some text
</div>

I have a container which has some text. As the size of the container is reduced, the text must be truncated. But I want the truncation to only happen till a specific minimum width of the container beyond which the text should be hidden. Is it possible to achieve this using only CSS?

.container {
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
<div class="container">
  This is some text
</div>

Codepen: https://codepen.io/hari-rahul/pen/PwYRweV

Share Improve this question edited 12 hours ago Naeem Akhtar 9981 gold badge9 silver badges23 bronze badges asked 14 hours ago Hari RahulHari Rahul 311 silver badge5 bronze badges New contributor Hari Rahul is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Add a comment  | 

2 Answers 2

Reset to default 4

Here is an example using clamp() where the item is hidden below 50px of width.

Resize of the container to test:

.container {
  width: 200px;
  border: 1px solid;
  overflow: hidden;
  resize: horizontal;
}

.container p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin: 0;
  width: clamp(0px, (100% - 50px)*9999, 100%);
}
<div class="container">
  <p>This is some text</p>
</div>

What you require is a container query which requires that the text have a wrapper such as a p tag.

.container {
  container-type: inline-size;
  max-width: 200px;
}

p {
  outline: 1px solid red;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}


@container (max-width: 100px) {
  p {
    display: none;
  }
}
<div class="container">
  <p>This is some text</p>
</div>

Codepen Demo

本文标签: htmlHow to truncate only till a specific widthStack Overflow