Search code examples
htmlcsspositioning

On one line, two elements left-most, one right-most, contents vertically centered on the line, no fixed sizes


My apologies if similar questions already exist (I know they do), but I didn't really find what I was looking for and I'm getting crazy here. I want the solution to work on Chrome; compatibility with other browsers is optional.

Let me draw a picture of what I want, hoping my ASCII art won't get messed up. The line of xs represents the page width:

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
,-----------.   ,---.                                      
| Contents  |   |   |                            ,--------.
|           |   | B |                            | some C |
| A         |   |   |                            `--------'
`-----------'   `---'                                      

A and B should be as close of each other as possible, and A should touch the left of my window. C should touch the right of my window. Between B and C is an empty area that varies with respect to the three elements sizes. If C has a smaller height than A or B, I want it to be centered vertically on the line. I'd like to not to use javascript for layout.

I tried many things, among which:

  • Tables won’t do it, because they distribute size evenly OR I need to fix dimensions, which I can’t (content is dynamic, although the sizes are in a fixed (probably definable) range)
  • Floated divs won’t be able to center their contents vertically unless displayed as table-cells, but then I cannot float them anymore.

(This sort of thing would be trivial in any modern GUI toolkit. Why are the web standards lagging so far behind?)


Solution

  • http://jsfiddle.net/zEaK9/

    HTML:

    <div class="left main">
        <div class="container">
            <div class="contents"></div>
        </div>
    </div>
    <div class="center main">
        <div class="container">
            <div class="contents"></div>
        </div>
    </div>
    <div class="right main">
        <div class="container">
            <div class="contents"></div>
        </div>
    </div>
    

    CSS:

    div{
        height:100px;
    }
    .main{
        display:table;
    }
    .left{
        background:blue;
        width:65px;
        float:left;
    }
    .center{
        background:green;
        width:100px;
        float:left;
    }
    .right{
        background:orange;
        width:65px;
        float:right;
    }
    .container{
        display:table-cell;
        vertical-align:middle;
    }
    
    .contents{
        margin:auto;
        height:20px;
        width:20px;
        background:lightGrey;
    }