DIV inline-block + width 100%

clavish picture clavish · Aug 2, 2012 · Viewed 34.1k times · Source

I can't display a few DIV's in one line. display: inline-block and float: left doesn't work. My site width is not fixed so I want it to be dynamic to fit any width of screen.


HTML:

<div id="all">
    <div id="a">25px</div>
    <div id="b">200px</div>
    <div id="c">
        <div id="c1">100%</div>
        <div id="c2">100%</div>
        <div id="c3">100%</div>
    </div>
    500px
</div>

CSS:

DIV {
    margin:5px;
    font-size:10px;
}

DIV#all {
    width:500px;
    border:1px dotted black;
}

DIV#a {
    display:inline-block;
    width:25px;
    height:200px;
    border:1px solid red;
    color:red;
}

DIV#b {
    display:inline-block;
    width:150px;    
    height:200px;
    border:1px solid green;
    color:green;
}

DIV#c {
    display:inline-block;
    width:auto;
    height:200px;
    border:1px solid blue;
    color:blue;
}

DIV#c1 {
    width:auto;
    border:1px dotted blue;
    color:blue;   
}

DIV#c2 {
    width:auto;
    border:1px dotted blue;    
}

DIV#c3 {
    width:auto;
    border:1px dotted blue;   
    color:blue;
}​

Live Demos:

Answer

xec picture xec · Aug 2, 2012

The problem with your current attempt is the width: 100%; on the third column div#c. 100% here will be 100% of its parent - which contains all three columns. Depending on what level of flexibility you want you have a few options.

If the site width is fixed, set a fixed width for the third column.

If you want the third column to stretch to its content, set max-width.

If you want the third column to stretch to fill its parent, you're probably better off with (css) tables.

Check out http://somacss.com/cols.html for a great resource on css column layout.