MatTaNg
MatTaNg

Reputation: 895

Stop word wrapping

I am trying to make a description box which shows only part of a description. I would like the user to have the ability to click a button to reveal the rest of the description.

To account for different device sizes I can't just cut the text off after a certain amount of characters. I would like the text to display for the whole width of the screen and get cut off.

I have put the CSS class "white-space: nowrap" onto my div which makes the text not wrap but now it is going completely outside the div.

  <div class="col"><p style="white-space: nowrap; font-size:12pt">{{description}}</p></div>

If I could get my div to just cut the text off if it reaches the end of the div I think I should be okay.

How do I basically tell my div; "Hey, display this description on only one line and if it is longer then just cut it off."

Upvotes: 0

Views: 221

Answers (3)

Adam Jenkins
Adam Jenkins

Reputation: 55613

Here's how to cut the text off in a single line, based on the width of the element:

document.querySelector('button').addEventListener('click',function() {
   document.querySelector('p').classList.toggle('expanded');  
});
p {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;  
  }

p.expanded {
  text-overflow: initial;
  white-space: initial;
}

p.expanded+button { display: none; }
<p>n vitae aliquet mi. Aliquam imperdiet orci ipsum, vel facilisis quam venenatis a. Donec rhoncus lectus sit amet fringilla accumsan. Vivamus convallis risus eu porta porta. Aenean blandit varius ultrices. Integer metus tellus, tristique ac cursus quis, tempor sit amet turpis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam accumsan laoreet orci eget fringilla. Maecenas ac imperdiet orci. Morbi imperdiet accumsan augue nec ultrices. Donec arcu felis, molestie a metus in, feugiat molestie libero. In sit amet odio ut neque posuere ultrices eu at felis. Donec et bibendum ligula, at varius massa. In velit neque, egestas in velit venenatis, sagittis ornare odio.</p>
<button>More...</button>
  

Upvotes: 4

Lahiru Jayakody
Lahiru Jayakody

Reputation: 5400

use these styles to the paragraph. this is what you expect

.p {
  text-overflow: ellipsis;

  /* Required for text-overflow to do anything */
  white-space: nowrap;
  overflow: hidden;
}

Upvotes: 0

Johannes
Johannes

Reputation: 67738

Add overflow: hidden;:

<div class="col"><p style="white-space: nowrap; font-size:12pt; overflow: hidden;">Bla blablablablablablablablablablab blablabla blabla blablabla blabla bla ablablablablab blablabla blabla blablabla blabla bla ablablablablab blablabla blabla blablabla blabla bla ablablablablab blablabla blabla blablabla blabla bla</p></div>

Upvotes: 0

Related Questions