Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-shrink text with CSS/HTML

Tags:

html

css

I am trying to display 2 values on the same row and give the one on the right priority to grow (it is a mobile app and needs to detect the width of the screen and "squash" the left cell to be smaller.

Here is my attempt: http://jsfiddle.net/rodneyjoyce/TxBhD/

HTML

<div id="screen">
    <div id="leftDesc">This is a Long Description</div>
    <div id="rightDesc">1000</div>
</div>

CSS

#screen
{    
    width: 200px;
}

#leftDesc
{    
    display: inline-block;
    overflow: hidden;
    float: left;
    height: 20px;
    max-width:160px;
    color: blue;
}

#rightDesc
{   
    float: right;
    display: inline-block;
    text-align: right;
    color: red;
}

What should happen: Increase "1000" to "1000 000". Blue text should chop off the end of the word "Description" and the red and blue text should stay on the same line.

Disclaimer: I am not very good at CSS - in XAML I use the * value on width so that a cell auto-grows and shrinks the others.

I do not want to use Javascript or JQuery.

like image 411
Rodney Avatar asked Jun 24 '13 02:06

Rodney


2 Answers

I'm not sure if you can dynamically change the size of your floated elements with CSS based on the content, but part of the problem can be solved with:

Adding to #leftDesc:

text-overflow:ellipsis;
white-space:nowrap;

The white-space property keeps the text on one line; text-overflow should be pretty self-explanatory.

JSFiddle

like image 139
jackweinbender Avatar answered Oct 07 '22 00:10

jackweinbender


Use the flexible box layout:

#screen
{    
    width: 200px;
    display: -webkit-flex;
    display: -moz-flex;
    display: flex;
}

#leftDesc
{    
    overflow: hidden;
    height: 20px;
    color: blue;
    white-space:nowrap;
}

#rightDesc
{   
    text-align: right;
    color: red;
}

I've removed your floats and your inline-blocks, and added display: flex to get the boxes to behave.

I've also added white-space:nowrap; to make sure the description gets cut off, like you've asked.

I've also removed max-width:160px;, because it didn't appear to have any effect in this scenario.

Keep in mind that this will not work in IE.

like image 21
uber5001 Avatar answered Oct 07 '22 01:10

uber5001