Simulator88
Simulator88

Reputation: 637

Set div width by text length

I made this jquery:

Define the holder div:

var cimHolder = componentWrapper.find('.cim_holder');

If title exist data equals title:

    if(data.attr('title') != undefined && !isEmpty(data.attr('title'))){
                cimData = data.attr('title');
                cimExist = true;

        }

If title exists show it in the div:

        if(cimExist){
            cimHolder.css('width', 'auto');//reset
            cimHolder.html(cimData);

Set the div widht by character length:

            var hossz = cimData.length*6.5;
            //console.log(cimData);
            if(parseInt(cimHolder.css('width'), 10)>200){
                cimHolder.css('width', hossz+'px');
            }
            }

But by this way if you get a lot of wide characters, the div will be small, but when you get a lot of narrow characters it will be long. How to fix this?

EDIT: if I set the div auto or 100% it will not fit by the text, just use all the space in the screen.

Upvotes: 3

Views: 12461

Answers (3)

Mic
Mic

Reputation: 523

inline elements like span or a -tags (display: inline;) are only as wide as their content. If you have a block element like a div (display: block;) the width is 100% by default. so if you don't need a block element, you can use display: inline;

Has you log the value of parseInt(cimHolder.css('width'), 10) ? Maybe the "px" unit can not be parsed correctly.

Greetings

Upvotes: 2

Tschallacka
Tschallacka

Reputation: 28742

Why not use

overflow:visible;

That way it always has to match the width of the containing text, no matter how long.

Upvotes: 0

user1796666
user1796666

Reputation:

Well you can use these two css properties:

max-width: 100px;
min-width: 50px;

Upvotes: 0

Related Questions