CSS - how to trim text output?

2019-07-23 13:17发布

问题:

I have an arbitrary amount of text that will be displayed in a confined space.

How can I trim the output so that whatever is "beyond" the box is not displayed, or how can I force the box to create a vertical scroll bar?

回答1:

The overflow property. You can set the value to hidden to hide the data and scroll to scroll the data.

<div class="text">this is some text that would be very long...</div>

//Hidden
.text
{
    overflow: hidden;
    width: 50px;
    height: 50px
}
//Scroll    
.text
{
    overflow: scroll;
    width: 50px;
    height: 50px
}


回答2:

For HTML:

<div id="smallBoxWithLotsOfText">There is way more text in here than what
    I have typed.  I mean, this text is long.  There is lots of it.  
    You can't even imagine how long this text is gonna get.  No joking.  
    It's long; it's very, very long.  It keeps going, and going, and going. 
    It's the Energizer Bunny of text.  Like, seriously dude.  It's crazy.  
    Absolutely crazy.
</div>

Try CSS:

#smallBoxWithLotsOfText {
    width: 100%;
    height: 100px;
    overflow: auto;
}

The height property tells the box how high to be. The overflow property tells the box to add a scroll bar when the contents get bigger, but not to always have a scrollbar (like scroll does).

You can see this in action.



回答3:

usually 'overflow: auto' should work if there is a set height/width. You can force a scroll bar with 'overflow: scroll'. You can hide anything with 'overflow: hidden;'

The key to overflow with CSS styles is the height and width have to be determined by the browser in order for it to know when to start overflowing.



回答4:

Take a look at overflow. overflow: hidden clips content, overflow:Scroll adds a scrollbar.



回答5:

How can I trim the output so that whatever is "beyond" the box is not displayed

Use overflow: hidden

How can I force the box to create a vertical scroll bar?

Use overflow: auto. To use this, though, make sure you have a width/height specified on the box



回答6:

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

More ways to trim text and show ellipsis can be found here: http://blog.sanuker.com/?p=631



标签: css text scroll