Here is my screenshot:
and this is my following code :
<div style="background:green; width:100px; height:27px;">
This is text to be written here
</div>
My question, how to trim my text if it goes out of the div? I want my text is being trimmed like the second box. Please tell me how to do it.
Here is my screenshot:
and this is my following code :
<div style="background:green; width:100px; height:27px;">
This is text to be written here
</div>
My question, how to trim my text if it goes out of the div? I want my text is being trimmed like the second box. Please tell me how to do it.
Share Improve this question asked Feb 23, 2017 at 5:28 NameName 4083 gold badges9 silver badges23 bronze badges 1- plnkr.co/edit/jpobTRIYUCfukv95Dq1q?p=preview – Sharma Vikram Commented Feb 23, 2017 at 5:37
7 Answers
Reset to default 4Use the overflow
and text-overflow
css rule
div {
overflow: hidden
text-overflow: hidden
}
<div style="background:green; width:100px; height:27px;">
This is text to be written here
</div>
text-overflow
will only work when the container's overflow property has the value hidden, scroll or auto and white-space: nowrap as described in the link below
This site talks about the topic well if you'd like to learn more
You have to add this to your style.
text-overflow: ellipsis; overflow: hidden; white-space: nowrap;
Demo
Set the style text-overflow, white-space, overflow
property:
<div style="background: green;height: 27px;overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 100px;">
This is text to be written here
</div>
Use text-overflow: ellipsis;
property with white-space: nowrap; overflow: hidden;
.
So, your code will look like this
<div style="background:green; width:100px; height:27px;text-overflow: ellipsis;white-space: nowrap; overflow: hidden;">
This is text to be written here
</div>
Here is a good explanation of what's going on.
Set the following style properties:
text-overflow:ellipsis
white-space:nowrap
overflow:hidden
<div style="background:green; width:100px; height:27px; text-overflow:ellipsis; white-space:nowrap; overflow:hidden;">
This is text to be written here
</div>
Add this css to your code:
div{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
<div style="background:green; width:100px; height:27px;">
This is text to be written here
</div>
Here is the code to trim the text using css or jquery
jquery
<div id="text">
This is text to be written here
</div>
<script type="text/javascript">
$(document).ready(function(){
var text =$('#text').html();
if(text.length>20){
$('#text').html(text.substr(0,20)+'...') ;
}
});
Css
<div id="css">
This is text to be written here
</div>
#css {
text-overflow: ellipsis ;
background:green;
width:100px;
height:27px;
display:inline-block;
overflow: hidden;
white-space:nowrap;
}
Thanks