skip to Main Content

I know we can limit text to certain characters using Ellipsis or even use JavaScript. But I am wondering if there is no JavaScript available, and I don’t want Ellipsis(…) at the end of my text, is this do able with just using CSS?

For instance say I have the following HTML – If I want to limit myText to just 20 characters(with spaces) how would I do that?

<div class="myDiv">
  <p class="myText">HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets and scripting
    languages such as JavaScript.</p>
</div>

3

Answers


  1. The short answer is not without JS.

    An approximation is if you know the font size and the user is not zooming, then you can do overflow hidden

    .myText {
        width: 151px; /* Adjust this value based on your specific font and size */
        white-space: nowrap;
        overflow: hidden;
       
    }
    <div class="myDiv">
      <p class="myText">HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets and scripting
        languages such as JavaScript.</p>
    </div>
    Login or Signup to reply.
  2. There is a CSS ‘length value’ of ch.

    p {
      overflow: hidden;
      max-width: 75ch;
      white-space: nowrap;
    }
    
    Login or Signup to reply.
  3. I think the only way without Javascript is to use a monospace font and the CSS ch unit

    .myDiv {
      width: 20ch;
      overflow: hidden;
      font-family: Courier, monospace;
      white-space: nowrap;
    }
    <div class="myDiv">
      <p class="myText">HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets and scripting
        languages such as JavaScript.</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search