Search code examples
csshtmldreamweavercentering

How can I centre a div between 2 floating divs


hi I am having a problem centering my content div between my left and right sidebars. My left and ride side bars are floating and there isn't a float:center. The only way I can center it is using padding but that makes my center div go underneath my sidebars.


Solution

  • Here's a working one.

    Use margin: 0 auto; will get your element centered most of the time. (Quick note: your element must have a declared width for this to work.)

    The margin: 0 auto; rule is shorthand for 0 top and bottom margin, and automatic left and right margins. Automatic left and right margins work together to push the element into the center of its container.

    The margin: 0 auto; setting doesn't work perfectly in every centering situation, but it works in a whole lot of them.
    reference: You Can't Float Center with CSS

    HTML

    <div class="leftsidebar">a</div>
    <div class="rightsidebar">b</div>
    <div class="content">c</div>
    

    CSS

    .leftsidebar 
    { 
    height: 608px; 
    width: 60px; 
    background:red; 
    float:left; } 
    
    .rightsidebar 
    { 
    background:blue; 
    height: 608px; 
    width: 163px; 
    float:right; 
    } 
    
    .content 
    { 
    width: auto; //or any width that you want
    margin:0 auto;
    background:yellow;
    }