Wes P
Wes P

Reputation: 9870

Centering inline-block element between floats

I have a header which contains elements on the left, middle, and right. To achieve this, I have a float left div, a float right div, and a margin 0 auto div, as exampled here: http://jsfiddle.net/huggz/uuq4Z/1/

<div style="text-align: center;" >

    <div style="width: 200px; height: 100px; background: red; float: left;"></div>
    <div style="width: 100px; height: 100px; background: blue; float: right;"></div>

    <div style="background: green; margin: 0 auto; display: inline-block;">
        <div style="width: 150px; height: 100px; background: orange;"></div>
    </div>

</div>

I have the middle div set inline-block in an attempt to allow the middle content to vary in width. However doing so, makes the margin: auto treat the floated elements like they're actually holding space. If left is wider than right, I end up with a slightly (or not so slightly) off-centered middle element.

Is there a way to do what I'm trying to do, preferably without resorting to scripts. If that need be the case, I'd rather just deal with the consequences of making middle column fixed width.

[EDIT] I should mention, there are instances where no middle or right content will exist.

Upvotes: 1

Views: 209

Answers (2)

Marc Audet
Marc Audet

Reputation: 46775

I think you want something like this:

<div>
    <div style="width: 200px; height: 100px; 
                background: red; float: left;"></div>
    <div style="width: 100px; height: 100px; 
                background: blue; float: right;"></div>

    <div style="background: green; display: block; margin: 0 100px 0 200px;">
        <div style="width: 150px; height: 100px; 
                    background: orange; margin: 0 auto;"></div>
    </div>

</div>

with the fiddle: http://jsfiddle.net/audetwebdesign/AFQV3/

I would keep the center element in-flow (not floated) and set the left and right margins so allow for the left and right floated elements.

The center div will then have a block of space in which you can set other elements, for example, the orange div, which you center between the floats.

Upvotes: 1

r3bel
r3bel

Reputation: 1370

you can use position instead of float: http://jsfiddle.net/uuq4Z/5/

<div style="text-align: center; position: relative;" >

    <div style="width: 200px; height: 100px; background: red; position: absolute; left: 0; top: 0"></div>
    <div style="width: 100px; height: 100px; background: blue; position: absolute; right: 0; top: 0;"></div>
    <div style="background: green; display: inline-block;">
        <div style="width: 150px; height: 100px; background: orange;"></div>
    </div>

</div>

Upvotes: 1

Related Questions