Search code examples
cssxhtmlxhtml-1.0-strict

css to work with dynamic 1, 2, 3 column layout based on if column exist with 1 set of rules


Note:

In some situations elements with display:table-cell; have space at the top that is not padding, or margin and border-collapse:collapse; doesn't fix it either. You need to also use vertical-align:text-top;. Another users question on the subject.

Original question

I create my template files with php and have been using 3 different sets of css rules for the columns depending on if there is 1, 2 or 3 columns. Im wondering if I can get 1 set of rules to work.

glimpse of the php idea

if($this->_data['left']!=NULL)
    echo "<div id='left'>{$this->left}</div>";
if($this->_data['right']!=NULL)
    echo "<div id='right'>{$this->right}</div>";
echo "<div id='content'>{$this->main}</div>";

#left and #right would be fixed width and to the left and right. The #main would be in center and use up the rest of the #wrappers width. so if there wasnt a #right the #main would fill the space where #right would have been.

<!-- 3 column -->
<div id='container'>
    <div id='left'></div>
    <div id='main'></div>
    <div id='right'></div>
</div>

<!-- 2 column -->
<div id='container'>
    <div id='left'></div>
    <div id='main'></div>
</div>
<!-- or -->
<div id='container'>
    <div id='main'></div>
    <div id='right'></div>
</div>

<!-- 1 column -->
<div id='container'>
    <div id='main'></div>
</div>

Solution

  • You can use display:table property for this. Write like this:

    #container{
        display:table;
        width:100%;
    }
    #container > div{
        display:table-cell;
        height:50px;
    }
    #left, #right{
        width:100px;
        background:red;
    }
    #right{
        background:green;
    }
    #main{
        background:blue;
    }
    

    Check this http://jsfiddle.net/HXaPR/