Search code examples
csscss-floatcentermargin

Element with margin: auto overlaps floated elements, solution?


I have a div which on most pages I want centered in my content area, I'm accomplishing that via "margin:5px auto;".

On a specific page I want to put an image and caption to the right, (like <div><img /><cite></cite></div>) and have my original div centered in the remaining space. When I set my new div as float:right; it simply overlaps my original div.

What would be the best way to solve this such that my original div could be centered on most pages, but adjust to the side if I place an element beside it? (or I could use a table, or inline styles :(

I have a jsfiddle here http://jsfiddle.net/nhaskins/zjZth/

Thanks.

EDIT

To clarify I want something where I can have #right be of arbitrary width, #left will center in the remaining width, and the text will clear below #left and flow around #right. If I don't find a solution my fallback will be to override the margin of #left with inline styles to position it properly for any given page.


Solution

  • Updated Answer Using jQuery:

    http://jsfiddle.net/zjZth/8/

    $(document).ready(function(){
        var margin = (($('#content').width() - $('#right').width()) - $('#left').width() ) / 2;
        $('#left').css('margin-left', margin + 'px');
    });
    

    Original Answer:

    Easiest solution I can come up with is putting your floating right div outside of your content, then giving your content a right margin equal to the width of your floated div.

    Updated fiddle: http://jsfiddle.net/zjZth/6/

    HTML:

    <div id="right"></div> 
    <div id="content">
    <div id="left"></div>
    <p>Lorem ipsum etc. etc. hkf uhuhek jfhksd jhgklh wgeluih e d shd ed k uhue f vgkdgku  e fudu ghf ugefkiu gek fwioeugf i ghdsi gusdui djhfk uhuhek jfhksd jhgklh wgeluih e d shd ed k uhue f vgkdgku  e fudu ghf ugefkiu gek fwioeugf i ghdsi gusdui djhfk uhuhek jfhksd jhgklh wgeluih e d shd ed k uhue f vgkdgku  e fudu ghf ugefkiu gek fwioeugf i ghdsi gusdui djhfk</p>
    </div>
    

    And for the CSS:

    #content {
        padding: 5px; 
        margin-right:200px;
    }
    
    #right {
        background: rgba(0,0,255,0.8);
        float: right;
        width: 200px;
        height: 200px;
        margin: 5px;
    }
    
    #left {
        background: red;
        margin: 5px auto;
        width: 200px;
        height: 120px;
    }