skip to Main Content

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?

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

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search