views:

46

answers:

5

what's the best way to force DIV to fill specified width? I have the following code that generates and assign width to DIV:

function createLabel(str) {
        var textDiv = document.createElement('div');
        textDiv.style.width = '200px';
        textDiv.style.display = 'inline';
        textDiv.appendChild(document.createTextNode(str));
        return textDiv;
}

I want created DIV's to have the same width, whatever text length is.

alt text

A: 
<div style="width : x%">

x= numeric value

Richa
A: 

I'd go with the CSS width property, paying attention to the box model problem. Unless there is some specific requirements.

streetpc
A: 

Giving it a width attribute?

e.g.

<div style="width: 300px"> 

or do you mean something else? In that case, please elaborate on your question.

Pekka
A: 

If you set the width to a specific value in PX, it should always have the same width. Also you JavaScript looks good. So where is the problem with your solution.

Kau-Boy
+1  A: 

You might run into trouble specifying both a width and display = 'inline'. The width won't have any effect. You'll need to keep the default display mode for a div element, i.e. block. If you need other elements at the same horizontal position, you'll need to use float as well.

Graham Clark