Search code examples
jqueryhtmlcenter

Keep div centered while page width grows/shrinks


I have a floating left div so that it wraps the content. I would like to center this div. Unfortunately, since I do not know the exact width of this div, I cannot use margin: 0 auto;. So, I decided to use jQuery to center the div. I was able to do this correctly by using .outerWidth(). The issue is, I would like the div to remain centered when the page grows/shrinks. I thought setting the margin-left to a percentage would accomplish this, but it does not. Is there a way to do this?


Solution

  • You don't need the exact width of a div to center it. You can see it working here jsfiddle.net/GkGBT

    CSS

    body{
        text-align:center;
     }
    .centerdiv{
       background:blue;  
       display:inline-block;
       margin-left:auto;margin-right:auto;
       text-align:left;
     }
    

    HTML

    <div class="centerdiv"></div>