user1632298 user1632298 -4 years ago 191
HTML Question

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:

cimHolder.css('width', 'auto');//reset

Set the div widht by character length:

var hossz = cimData.length*6.5;
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.

Answer Source

Why not use


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download